Thursday, May 28, 2009

How to do check and uncheck all record on ASP.Net GridView using JavaScript and ASP.Net


When we accessing common webmail site like Gmail, Yahoo!mail or Hotmail, we will see a feature that allow us to select all message listed with a single click, either on a link says "Check All" or a checkbox that will trigger same action somewhere on its header, for the same if want to uncheck them. To do such feature above on ASP.Net Application, I would say impossible with just using standard control, ASP.Net GridView for instance, you would need to get enhanced control or else programmatically coding it in your application :)

On every application that was built by our team, we try to as much as possible not to do it on server side, as it will increase data round trip which as we all know will reduce application performance. So, combination of ASP.Net, Ajax and JavaScript come as a solution.

First we need to have to add TemplateField on GridView to show CheckBox, in our approach we also use a CheckBox on this column header to trigger Check/UnCheck operation by bind a JavaScript function on this CheckBox's OnChange event.

Next, we will need to write down JavaScript function that will be used to perform Check/UnCheck operation, our code is as follow:

var checkMes = new Array();

function addCheckMe(checkMe_CtlId)

{

checkMes.length++;

checkMes[checkMes.length-1]=checkMe_CtlId;

}

function doCheckUncheckAll()
{
var tmpCheckMe;
var checkAll=$get("CheckAll");

for(i=0;i { tmpCheckMe=$get(checkMes[i]); tmpCheckMe.checked=checkAll.checked; }
}


You may see, we have one array to store list of checkbox, a function to fill that array and another function to trigger Check/Uncheck operation.

Okay with done with defining checkbox and JavaScript thing, next we need to call addCheckMe function within our ASP.Net code as GridView will define checkbox dynamically, so ... we add a function to handle GridView's RowDataBound event

protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{

string addCheckMeScript = "";
CheckBox CheckMe = (CheckBox)e.Row.FindControl("CheckMe");

if (CheckMe != null)
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), String.Format("OnGrdCheckMeRegister_{0}", e.Row.RowIndex), String.Format("addCheckMe('{0}');", CheckMe.UniqueID.Replace("$","_")), true);
}
}

And voilla we get as we have expected ... code with smile :)

No comments:

Post a Comment