Consider a situation in which you have a checkbox template column in Datagrid web server control. If you only have 8-10 rows being displayed than you can manually select all the checkboxes. But consider selecting hundreds of rows manually. In this article I will show you that how you can select all the checkboxes quickly and more efficiently.

 

Introduction:

Consider a situation in which you have a checkbox template column in Datagrid web server control. If you only have 8-10 rows being displayed than you can manually select all the checkboxes. But consider selecting hundreds of rows manually. In this article I will show you that how you can select all the checkboxes quickly and more efficiently.

Selecting all checkboxes manually:

First let's see that how we can select all the checkboxes manually by clicking each checkbox one at a time. Our user interface is very simple which consists of two bound columns and one template column, which contains the checkbox.

Here is the code to select the checkboxes. This code is fired when the "Approve Articles" button is clicked.

// Iterates through the DataGrid column and select the checked articles

foreach(DataGridItem dgi in myDataGrid.Items)

{

CheckBox chkSelected = (CheckBox) dgi.FindControl("chkActive");

if(chkSelected.Checked == true)

{Response.Write(dgi.Cells[0].Text);

}

}

<ItemTemplate>
<asp:CheckBox id="chkActive" runat="server"></asp:CheckBox>
</ItemTemplate>

Let's see how we can make use of the "Select All" option which will automatically select all the checkboxes in the Datagrid control. The "Select All" checkbox is simply created in the header.

<HeaderTemplate>
Select All
<asp:CheckBox onclick="javascript:SelectAllCheckboxes(this);" id="chkAll" runat="server"></asp:CheckBox>
</HeaderTemplate>

As you can see that there is an onclick event attached to the "Select All" checkbox. When the Checkbox is clicked javascript method "SelectAllCheckboxes(this)" is executed.

<script language=javascript>
function SelectAllCheckboxes(spanChk){

// Added as ASPX uses SPAN for checkbox
var oItem = spanChk.children;
var theBox=(spanChk.type=="checkbox")?spanChk:spanChk.children.item[0];
xState=theBox.checked;

elm=theBox.form.elements;
for(i=0;i<elm.length;i++)
if(elm[i].type=="checkbox" && elm[i].id!=theBox.id)
{
//elm[i].click();
if(elm[i].checked!=xState)
elm[i].click();
//elm[i].checked=xState;
}
}
</script>

This is all you have to do to get the select all functionality. I hope you like the article, Happy coding !