日期:2014-05-17  浏览次数:20396 次

C#DataGrid数据绑定时的判断,求教
先声明,是DataGrid 不是GridView
<asp:DataGrid ID="Data_g" runat="server"></asp:DataGrid>

有3个字段需要绑定,A,B,C
需求1:字段A正常绑定<%#Eval("A") %>已完成
需求2:字段B,绑定在一个textbox上,要求当字段A="1"时,字段B的textbox只能看不能修改(只读)
当字段A="2"的时候,字段B的textbox正常
需求3:有4个ImageButton控件(B1,B2,B3,B4),当字段C="1"时,显示B1,B2,隐藏B3,B4(隐藏或禁用都可以)
当字段C="2"的时候,显示B3,B4,隐藏B1,B2(一样的,最好是禁用,隐藏的话,因为再DataGrid里,空间还占着,排版不好看)

求高手帮忙,求教,给出完整的代码,谢谢
 


------解决方案--------------------
<asp:DataGrid ID="Data_g" runat="server" OnItemDataBound="Data_g_ItemDataBound">




C# code
protected void Data_g_ItemDataBound(object sender, DataGridItemEventArgs e)
{
  if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
  {
    String A = DataBinder.Eval(e.Item.DataItem, "A").ToString();
    String B = DataBinder.Eval(e.Item.DataItem, "B").ToString();
    String C = DataBinder.Eval(e.Item.DataItem, "C").ToString();
    TextBox TextBox1 = e.Item.FindControl("TextBox1") as TextBox;
    if (A == "1") TextBox1.ReadOnly = true;
    ImageButton B1 = e.Item.FindControl("B1") as ImageButton;
    ImageButton B2 = e.Item.FindControl("B2") as ImageButton; 
    ImageButton B3 = e.Item.FindControl("B3") as ImageButton;
    ImageButton B4 = e.Item.FindControl("B4") as ImageButton;
    if (C == "1")
    {
      B3.Visible = false;
      B4.Visible = false;
    }
    else if (C == "2")
    {
      B1.Visible = false;
      B2.Visible = false;
    }      
  }
}