1

I am unable to access html checkbox on button click event.The checkbox is in gridview control.

<asp:GridView ID="_grvItems" runat="server"  />
              <Columns>
               <asp:TemplateField>
                        <ItemTemplate>

                            <input type="checkbox"  id="_chkSelect" />

                        </ItemTemplate>
                    </asp:TemplateField>

                </Columns>
                <PagerStyle CssClass="pgr" />
            </asp:GridView>

And I click on button then show me error "Object reference not set to an instance of an object." the code of button click event is :

 for (int i = 0; i < _grvItems.Rows.Count; i++)
    {
        HtmlInputCheckBox ch = (HtmlInputCheckBox)_grvItems.Rows[i].FindControl("_chkSelect");

        if (ch.Checked)
        {
            Response.Write("Checkbox is Checked");
        }}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • Welcome to Stack Overflow! Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Oct 19 '13 at 15:41

2 Answers2

0

The FindControl method is not returning the checkbox but returning null. This is why you are getting "Object reference not set to an instance of an object." When you would be accessing Checked property. You need to put runat="server" to make checkbox server accessible.

Change

 <input type="checkbox"  id="_chkSelect" />

To

 <input type="checkbox"  id="_chkSelect" runat="server" />
Adil
  • 146,340
  • 25
  • 209
  • 204
0

I would suggest to check for null:

HtmlInputCheckBox ch = (HtmlInputCheckBox)_grvItems.Rows[i].FindControl("_chkSelect");

if (ch!= null && ch.Checked)
{
    Response.Write("Checkbox is Checked");
}}

EDIT (As Adil pointed:

I would also change in markup:

<asp:GridView ID="_grvItems" runat="server"  />
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>    
                <input type="checkbox"  id="_chkSelect" runat="server" />    
            </ItemTemplate>
        </asp:TemplateField>        
    </Columns>
    <PagerStyle CssClass="pgr" />
</asp:GridView>
Community
  • 1
  • 1
afzalulh
  • 7,925
  • 2
  • 26
  • 37
  • Please change in markup also as I have shown in edit, and let us know in which line you are getting error. – afzalulh Oct 19 '13 at 18:43