简体   繁体   English

NullReference异常:当尝试检查gridview中的复选框字段时

[英]NullReference Exception: when try to check a check box field in gridview

I have a grid view with some check boxes. 我有一个带有一些复选框的网格视图。 So after the grid view get updated, I am trying to see whether one particular check box is checked or not. 因此,在网格视图更新后,我试图查看是否选中了一个特定的复选框。 However, I am getting an error says 但是,我收到一个错误说

Null Reference Exception was unhanded by user code 用户代码无法使用Null Reference Exception

My code: 我的代码:

<asp:TemplateField HeaderText="FollowUp" SortExpression="FollowUp">
   <EditItemTemplate>
      <asp:CheckBox ID="CheckBox1" runat="server" 
           Checked='<%# Bind("FollowUp") %>' />
   </EditItemTemplate>
   <ItemTemplate>
      <asp:CheckBox ID="chkFollowup" runat="server" 
           Checked='<%# Bind("FollowUp") %>' Enabled="false" />
   </ItemTemplate>
</asp:TemplateField>

Code-behind file: 代码隐藏文件:

protected void GViewSrvcCheck_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
    foreach (GridViewRow gRow in GViewSrvcCheck.Rows)
    {
        CheckBox fllwup = gRow.FindControl("chkFollowup") as CheckBox;

        if (fllwup.Checked)//this is the one causes the error
        { 
        }
    }
}

What goes wrong here? 这里出了什么问题? and how can I over come this problem? 我怎么能解决这个问题呢?

There are two possible problems: 有两个可能的问题:

  • The control couldn't be found 无法找到控件
  • It wasn't a CheckBox 它不是CheckBox

If you'd used a cast instead, you'd know which it was: 如果您使用的是演员,那么您就知道它是什么:

CheckBox followUp = (CheckBox) gRow.FindControl("chkFollowup");

It's almost always wrong to use as without a check for nullity afterwards. 使用之后几乎总是错误的, as没有检查无效性。

I suspect the problem is that the ID actually has something to identify the row within it as well... but with the above change you'd at least be able to tell which error path you were taking. 我怀疑问题是ID 实际上还有一些东西可以识别其中的行......但是通过上述更改,您至少可以判断出您正在使用哪个错误路径。

You'll probably have to change how you find the control - but so long as "not finding the control" is an error , I think it's reasonable to leave it throwing an exception. 你可能不得不改变你找到控件的方式 - 但只要“找不到控件”是一个错误 ,我认为让它抛出异常是合理的。 If the control not being present is a legitimate situation, you should explicitly handle it - but otherwise, showing an error page to the user and logging the exception (eg with ELMAH) is fine. 如果控件不存在是合法的情况,你应该明确地处理它 - 但是否则,向用户显示错误页面并记录异常(例如使用ELMAH)就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM