Wednesday, December 3, 2008

Code for check box check or uncheck in Grid View Using C#.net

-------------First You need to add the javascript code-----------------


var TotalChkBx;
var Counter;

window.onload = function()
{
//Get total no. of CheckBoxes in side the GridView.
TotalChkBx = parseInt('<%= this.gvCheckboxes.Rows.Count %>');
//Get total no. of checked CheckBoxes in side the GridView.
Counter = 0;
}


function HeaderClick(CheckBox)
{
//Get target base & child control.
var TargetBaseControl = document.getElementById('<%= this.gvCheckboxes.ClientID %>');
var TargetChildControl = "chkBxSelect";

//Get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");

//Checked/Unchecked all the checkBoxes in side the GridView.
for(var n = 0; n < Inputs.length; ++n)
if(Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl,0) >= 0)
Inputs[n].checked = CheckBox.checked;
//Reset Counter
Counter = CheckBox.checked ? TotalChkBx : 0;
}

function ChildClick(CheckBox, HCheckBox)
{
//get target base & child control.
var HeaderCheckBox = document.getElementById(HCheckBox);

//Modifiy Counter;
if(CheckBox.checked && Counter <> 0)
Counter--;

//Change state of the header CheckBox.
if(Counter < TotalChkBx)
HeaderCheckBox.checked = false;
else if(Counter == TotalChkBx)
HeaderCheckBox.checked = true;

Add onclick attribute for HeaderCheckbox like this:

In asp:CheckBox tag, add this: onclick="javascript:HeaderClick(this);"


Now add the following code in row_created event of GridView

if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
{
CheckBox chkBxSelect = (CheckBox)e.Row.Cells[1].FindControl("chkBxSelect");
CheckBox chkBxHeader = (CheckBox)this.gvCheckboxes.HeaderRow.FindControl("chkBxHeader");

chkBxSelect.Attributes["onclick"] = string.Format("ChildClick(this,'{0}');", chkBxHeader.ClientID);
}

Thats it!!!!!!!!!!

No comments: