Monday, July 16, 2007

How to select all run time generated Check Box.

How to select all run time generated Check Box.
Server Side Code in C#
//This function will fetch all the controls in the page
//you can make a filter based on control you want using
//"UnderlyingSystemType.Name" property
//Here recursive function used to get into controls inside controls
private void CheckBoxSelection(ControlCollection ctl, bool chkFlg)
{
CheckBox chkBox;
foreach (Control con in ctl)
{
if (con.GetType().UnderlyingSystemType.Name == "CheckBox")
{
chkBox = (CheckBox)Page.FindControl("UserControl").FindControl(con.ID);
chkBox.Checked = chkFlg;
}
if (con.HasControls())
{
CheckBoxSelection(con.Controls, chkFlg, chkIsModel);
}
}
}
//Same way you can get the controls value
private void GetSelectedCheckBoxValue(ControlCollection ctl)
{
ArrayList arrSelectedValue = new ArrayList();
CheckBox chk1;
foreach (Control con in ctl)
{
if (con.GetType().UnderlyingSystemType.Name == "CheckBox")
{
chk1 = (CheckBox)Page.FindControl("UserControl").FindControl(con.ID);
if (chk1.Checked)
arrSelectedValue.Add(con.ID);
}
if (con.HasControls())
{
GetSelectedCheckBoxValue(con.Controls);
}
}
}
Client Side Code in JavaScript supported by IE, Netscape and Mozilla
function CheckBoxSelection(flg)
{
// This line gives all the "Input" control in a page
var chk = window.document.getElementsByTagName("Input");
for (i =0;i<chk.length;i++)
{
// based on the ID prefix you can put condition
if (chk[i].id.indexOf("chk") != -1)
{
if (flg == "false")
{
chk[i].checked = false;
}
else
{
chk[i].checked = true;
}
}
}
}
Call Java script function from Code behind
rdoSelectAll.Attributes.Add("OnClick", "CheckBoxSelection('true')");
rdoClearAll.Attributes.Add("OnClick", "CheckBoxSelection('false')");
Note: rdoSelectAll and rdoClearAll is radio button controls
Generate runtime Check Box controls
private void GenerateModelTable(string[] modelNames)
{
Table tblModel = new Table();
for (int count = 0; count < modelNames.Length; count++)
{
TableRow trModel = new TableRow();
TableCell tcChkModel = new TableCell();
TableCell tcModel = new TableCell();
CheckBox chkModel = new CheckBox();
chkModel.ID = "chk" + "_" + modelNames[count];
tcChkModel.Controls.Add(chkModel);
tcModel.Text = modelNames[count];
trModel.Controls.Add(tcChkModel);
trModel.Controls.Add(tcModel);
tblModel.Controls.Add(trModel);
}
pnlModel.Controls.Add(tblModel);
}

No comments: