Friday, September 14, 2007

Selecting multiple checkboxes inside a GridView control

this article demostrates a very easy way to select/unselect all checkboxes in gridview. The magic method is using a headertemplate as follows:

Making a CheckAll functionality


To add a check-all functionality in the GridView, simply add a HTML CheckBox to the header template of the checkbox column.

<HeaderTemplate>
<input id="chkAll" onclick="javascript:SelectAllCheckboxes(this);"
runat="server" type="checkbox" />
</HeaderTemplate>

SelectAllCheckboxes JavaScript method:

<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>

Also we can use server side coding to implement select/unselect all in following way:


protected void btnSelectAll_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvResult.Rows)
{
CheckBox check = (CheckBox)(row.Cells[0].Controls[1]);
check.Checked = true;
}
}
protected void btnUnselectAll_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvResult.Rows)
{
CheckBox check = (CheckBox)(row.Cells[0].Controls[1]);
check.Checked = false;
}
}

No comments: