Sunday, June 19, 2011

Gridview Header Checkbox CheckAll

<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelectAll_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelect_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
-------------------------------------------------
HEADER CHECKBOX EVENT
-------------------------------------------------
protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkAll = (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
if (chkAll.Checked == true)
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
CheckBox chkSel =
(CheckBox)gvRow.FindControl("chkSelect");
chkSel.Checked = true;
}
}
else
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
chkSel.Checked = false;
}
}
}

-----------------------------------------------------------
ITEM CHECKBOX EVENT
------------------------------------------------------------
protected void chkSelect_CheckedChanged(object sender, EventArgs e)
{
int count = 0;
int totalChkBoxes = 0;
foreach (GridViewRow gvRow in GridView1.Rows)
{
totalChkBoxes += 1;
CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");

if (chkSel.Checked == true)
{
count += 1;
}
}

if (count == 0) // if no checkbox is selected then make header checkbox false.
{
CheckBox chkAll = (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
chkAll.Checked = false;
}

count = count + 1;
if (count == totalChkBoxes + 1)
{
CheckBox chkAll = (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
chkAll.Checked = true;
}

}
-------------------

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More