日期:2014-05-18  浏览次数:20464 次

菜鸟请教一个简单的问题!
我用DataGrid1动态加载CheckBox控件,现想当CheckBox被选中时能取得DataGrid1相应一值!程序如下高手帮看看!

        int   tcount=DataGrid1.Items.Count;
        for(int   i=0;i <tcount;i++)
            {
CheckBox   cbx=new   CheckBox();
cbx.ID= "ddd "+i.ToString();
DataGrid1.Items[i].Cells[0].Controls.Add(cbx);
            }

这上面的能添加,但下面取值就不行了!
int   tcount=DataGrid1.Items.Count;
for(int   i=0;i <tcount;i++)
{
    CheckBox   cb;    
    cb=(CheckBox)DataGrid1.Items[i].FindControl( "ddd "+i.ToString());
      if(cb.Checked==true)   //在这里报错   :未将对象引用设置到对象的实例
          {
ttt=DataGrid1.Items[i].Cells[1].Text.Trim().ToString();
          }

}


------解决方案--------------------
未将对象引用设置到对象的实例。
====>
说明Checkbox不存在

因为CheckBox是动态绑定的,所以在编历DataGrid之前,也应该将CheckBox绑定到DataGrid。
估计楼主是没绑定
------解决方案--------------------
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//为gridview添加删除提示。
e.Row.Cells[e.Row.Cells.Count - 1].Attributes.Add( "onclick ", "return confirm( '确定删除吗? '); ");
//为gridview当选中其中的checkbox时,该行颜色改变
CheckBox mycb = new CheckBox();
mycb = (CheckBox)e.Row.FindControl( "CheckBox1 ");
if (mycb != null)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowIndex % 2 == 0)
{
mycb.Attributes.Add( "onclick ", "changecolor(this.name, '#FFFFFF ') ");
}
else
{
mycb.Attributes.Add( "onclick ", "changecolor(this.name, '#EEEEEE ') ");
}
}

}
}

}
------解决方案--------------------
添加完checkbox后不要再绑定datagrid。databind();否则,checkbox会消失而获取不到,最好在datagrid中加模板列以达到楼主的目的