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?
There are two possible problems:
CheckBoxIf you’d used a cast instead, you’d know which it was:
It’s almost always wrong to use
aswithout 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.