在DataGrid中绑定复选框后,有一个button按钮触发一个事件,目的是要把复选框勾选的那行第3个单元格的数据显示在label(id="lb")中,代码如下:
public void bt_click(Object sender,System.EventArgs e)
{
foreach (DataGridItem dgItem in dg.Items)
{
    chkExport=(CheckBox)dgItem.FindControl("chkExport");
if(chkExport.Checked)
 {
lb.Text=dgItem.Cells[2].Text;
  }
}
}
但是运行后出现以下错误:
异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。
源错误: 
行 52: if(chkExport.Checked)请问这是怎么回事?比较急,在线等。

解决方案 »

  1.   

    foreach (DataGridItem dgItem in dg.Items)
    {
      CheckBox  chkExport=(CheckBox)dgItem.FindControl("chkExport");
    if(chkExport.Checked)
     {
    lb.Text=dgItem.Cells[2].Text;
      }
    }
      

  2.   

    chkExport=(CheckBox)dgItem.Cells[X].FindControl("chkExport");
      

  3.   

    for (int i=0;i<this.dgBrowse.Items.Count;i++)
    {
      CheckBox ch=(CheckBox)this.dgBrowse.Items[i].FindControl("chkExport");
      if (ch.Checked)
      {
        lb.Text=dgItem.Cells[2].Text;
      }
    }
    用这种方法试试,看看CheckBox的id是不是chkExport,注意大小写,应该不会错的,好运:)
      

  4.   

    我改成CheckBox chkExport=(CheckBox)dgItem.FindControl("chkExport");了,但还是老问题。
      

  5.   

    foreach (DataGridItem dgItem in dg.Items)
    {
        if (dgItem.ItemType != ListItemType.Item && dgItem.ItemType != ListItemType.AlternatingItem)
          continue ;
        chkExport=(CheckBox)dgItem.FindControl("chkExport");
    if(chkExport != null && chkExport.Checked)
     {
    lb.Text=dgItem.Cells[2].Text;
     }
    }