Smallest JavaScript Code for the SelectAll/UnSelectAll Checkbox in the GridView
This Article will explain with the JavaScript code snippet and the explanation of SelectAll/UnSelectAll check-box in the GridView of ASP.Net. Hope it will be useful for most of the friends who generally get stuck at this point where they need to write a JavaScript which will do this task. Learn Smallest JavaScript Code for the SelectAll/UnSelectAll Checkbox in the GridView.
Find Smallest JavaScript Code for the SelectAll/UnSelectAll Checkbox in the GridView
Hai Friends,
In this article I will try to explain the smallest code which is written in the JavaScript and will do the CheckAll/UnCheckAll for your GridView Check-box.
Let's
I have a GridView- name (default GridView1). This GridView contains a Checkbox named (chkSelect).
I have 2 link buttons- CheckAll (id- lnkCheckAll), UnCheckAll(id- lnkUnCheckAll).
By clicking the CheckAll link button, all the checkboxes in the gridView1 will be checked and similarly by clicking the UncheckAll link button, all the checkboxes in the GridView will get unchecked.
We will write first 1 small JavaScript code snippet which will take the Boolean parameter (true/false).
If the parameter is "true", then all the checkboxes inside the GridView1 will be checked and if is "false", then all the checkboxes in the GridView1 will be unChecked.
See below the JavaScript Code:
function SelectAll(b)
{
var grid = document.getElementById("<%= GridView1.ClientID %>");
// declare variable to contain the grid cell
var cell;
if (grid.rows.length > 0)
{
for (i = 1; i < grid.rows.length; i++)
{
cell = grid.rows[i].cells[0];
if (cell.childNodes[0].type == "checkbox")
cell.childNodes[0].checked = b;
}
}
}
Now we need to attach the "click" events of the link buttons to call this JavaScript function.
So i prefer to attach the "click" event in the RowDataBound event of the GridView as shown below:
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{ lnkSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" +
"true" + "')");
lnkUnSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" +
"false" + "')");
}
}
That's all. Cheers..
No need to do anything else.
In the RowDataBound event of the GridView, it is checking that if the Row id DataRow (means except Header and Footer), then it attach the "onClick" event for both the link buttons.
For the lnkSelectAll, it's passing the value as "true". It means it will check all the checkboxes and for the lnkUnSelectAll link button, it is passing the value as "false" so it will uncheck all the checkboxes which are inside the GridView.
Hope it will help for the coding prospective.
Nice article.
Also good real time code snippet which will help to other to implement the similar functionality.