0

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

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sas
  • 2,473
  • 6
  • 30
  • 47
  • possible duplicate of [What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) – John Saunders Feb 28 '12 at 19:30
  • You could be adding a header/footer that does not contain that template, so when checked in the Rows collection, it throws a null error (it can't find the object) – TimCodes.NET Feb 28 '12 at 19:32

1 Answers1

2

There are two possible problems:

  • The control couldn't be found
  • It wasn't a 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.

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.

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 (e.g. with ELMAH) is fine.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thnx, changing the check box ID "chkFollowup" From Item template field check box control to edit template field check box field fixed the problem. – Sas Feb 28 '12 at 19:45