vml19
vml19

Reputation: 3864

Select all Gridview record using CheckBox in the Gridview header

I am using checkbox in the gridview header to select all records in the gridview. this is the code behind method.

<asp:GridView ID="gvP" runat="server" AutoGenerateColumns="false" AllowPaging="false"
AllowSorting="false" DataKeyNames="PmtId" CssClass="list-table" HeaderStyle-CssClass="header"
EnableModelValidation="True">
    <Columns>
    <asp:BoundField DataField="PmtId" HeaderText="PmtId" ReadOnly="True" Visible="false" />
    <asp:TemplateField HeaderText="All" ItemStyle-CssClass="checkbox-col" HeaderStyle-CssClass="checkbox-col">
    <HeaderStyle HorizontalAlign="Center" />
    <HeaderTemplate>
    <input id="chkBoxAll" type="checkbox" onclick='javascript:checkAllBoxes("CLEAR_PT")' />
    </HeaderTemplate>
    <ItemTemplate>
    <asp:CheckBox runat="server" ID="chkSelect" />
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="S/No." ItemStyle-CssClass="seq-col" HeaderStyle-CssClass="seq-col">
    <ItemTemplate>
    <%# Eval("SNo")%>
    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
</asp:GridView> 

protected void chkSelectAll(string arg)
{
    if (arg.Equals("CLEAR_PT"))
    {
    CheckBox chkAll = gvP.HeaderRow.FindControl("chkBoxAll") as CheckBox;
    if (chkAll.Checked == true)
    {
    foreach (GridViewRow gvRow in gvP.Rows)
    {
    CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect") as CheckBox;
    chkSel.Checked = true;
    }
    }
    else
    {
    foreach (GridViewRow gvRow in gvP.Rows)
    {
    CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect") as CheckBox;
    chkSel.Checked = false;
    }
    }
    }
}

I am getting 'Object reference not set to an instance of an object' run time error in the following line.

if (chkAll.Checked == true)

Any Idea?

Upvotes: 2

Views: 5763

Answers (1)

Thit Lwin Oo
Thit Lwin Oo

Reputation: 3438

Your checkbox control in header template is html input control. You need to change as ASP.NET check box control. Change as server checkbox control and try. Actually check all and uncheck all can be done in client side javascript. No need postback.

Upvotes: 1

Related Questions