In this post, I will give an idea on how to check all and uncheck all CheckBox control nested in a Gridview using Javascript without postback.
At first, we need to know how to create a nested GridView control. Visist this post: Create a nested GridView control
Add the following code to inside the Columns tab of the GridView tab:
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<HeaderTemplate>
<asp:CheckBox ID="chkbAll" runat="server"/>
</ItemTemplate>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkbItem" runat="server" CommandArgument='<%# Eval("ProductID") %>'/>
</ItemTemplate>
</asp:TemplateField>
The GridView appeared as the following figure:
<script type="text/javascript" language="javascript">
function SelectAll(cb) {
var frm = document.forms[0];
for (i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].type == "checkbox" && frm.elements[i].name.indexOf('chkbItem') != -1) {
frm.elements[i].checked = document.getElementById(cb).checked;
}
}
}
function CheckChanged() {
var frm = document.forms[0];
var boolAllChecked;
boolAllChecked = true;
for (i = 0; i < frm.length; i++) {
e = frm.elements[i];
if (e.type == 'checkbox' && e.name.indexOf('chkbItem') != -1)
if (e.checked == false) {
boolAllChecked = false;
break;
}
}
for (i = 0; i < frm.length; i++) {
e = frm.elements[i];
if (e.type == 'checkbox' && e.name.indexOf('chkbAll') != -1) {
if (boolAllChecked == false)
e.checked = false;
else
e.checked = true;
break;
}
}
}
</script>
On RowDataBound event of GridView control, add the following cod
void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView drv = e.Row.DataItem as DataRowView;
if (e.Row.RowType == DataControlRowType.Header)
{
CheckBox cbhead = (CheckBox)e.Row.FindControl("ChkbAll");
cbhead.Attributes.Add("OnClick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("ChkbAll")).ClientID + "')");
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox cbrow = (CheckBox)e.Row.FindControl("ChkbItem");
cbrow.Attributes.Add("OnClick", "javascript:CheckChanged('" + ((CheckBox)e.Row.FindControl("ChkbItem")).ClientID + "')");
}
}
Hope this help!
0 comments:
Post a Comment