Tuesday, 18 March 2014

Asp.net gridview check all and uncheck all in a single Header Template checkbox


In this article I will explain how to 
check all and unchecked all in a single Header Template checkbox in GridView in ASP.NET.

First we need to add a check Box in GridView Header Template. Below is the design code for Check Box.

<asp:GridView ID="gvNew" runat="server" AutoGenerateColumns="false">
<Columns>
 <asp:TemplateField HeaderText="Monthly Report" HeaderStyle-Height="30px" FooterStyle-Height="25px">
<HeaderTemplate>
<asp:CheckBox ID="RbtIncludeMonthlyReportHT" runat="server" AutoPostBack="true" Text="Monthly Report"                                             OnCheckedChanged="RbtIncludeMonthlyReportHT_CheckedChanged" />
</ContentTemplate> 
</HeaderTemplate>
 <ItemTemplate>
<asp:UpdatePanel ID="upTest" runat="server">
<ContentTemplate>
<asp:CheckBox ID="RbtIncludeMonthlyReport" runat="server" AutoPostBack="true"   Checked='<%# Convert.ToBoolean(Eval("MonthlyReportFlag")) %>' />
 </ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>                                                      
</asp:TemplateField>
</Columns>
</asp:GridView>


RowDataBound event for binding data to check box

protected void gvNew_RowDataBound(object sender, GridViewRowEventArgs e)
    {
if (e.Row.RowType == DataControlRowType.Header)
        {
            CheckBox checkboxall = e.Row.FindControl("RbtIncludeMonthlyReportHT"as CheckBox;           
            if (checkboxall != null)
            {
                if (ViewState["MonthlyReport"] != null)
                {
                    checkboxall.Checked = (bool)ViewState["MonthlyReport"];
                    ViewState["MonthlyReport"] = null;
                }

            }
        }
}

Below is the code for saving check box information to DataBase.

protected void RbtIncludeMonthlyReportHT_CheckedChanged(object sender, EventArgs e)
    {
        className objClass=new className();
        CheckBox chk1 = default(CheckBox);
        chk1 = (CheckBox)gvNew.HeaderRow.Cells[0].FindControl("RbtIncludeMonthlyReportHT");
        bool MonthlyReport = chk1.Checked;
        ViewState["MonthlyReport"] = MonthlyReport;
        if (MonthlyReport == true)
        {          
           objClass. Month = 1;
           // Update information in DB
           objClass.GetMonthlyFlag();
        }
        else
        {           
            objClass. Month = 0;
           // Update information in DB
            objClass.GetMonthlyFlag();
        }
            if (MonthlyReport == true)
            {
                CheckBox chkMonth = (CheckBox)gvNew.HeaderRow.Cells[0].FindControl("RbtIncludeMonthlyReportHT");
            }
            else
            {
                CheckBox chkMonth = (CheckBox)gvNew.HeaderRow.Cells[0].FindControl("RbtIncludeMonthlyReportHT");
            }
        }

    }

No comments:

Post a Comment