Thursday, September 15, 2005

loop webcontrols in a page, and disable them all

all though we can loop Page.Controls, but not all of them are webcontrols( such as textbox, label, and dropdownlist). For example, the very first control in Page.Controls is the web form itself.
So what we really want to do is: loop every level of controls, see if they are the right type we are looking for, such as textbox, label, and dropdownlist, and disable them one by one.
the function needs be recursive, because there might be a usercontrol or panel in a page that contains web controls.



void DisableControls(ControlCollection controls)
{
foreach(Control c in controls)
{
try
{
TextBox tb= (TextBox)c;
tb.Enabled = false;
}
catch
{}
try
{
ListBox lb= (ListBox)c;
lb.Enabled = false;
}
catch
{}
try
{
RadioButtonList rb= (RadioButtonList)c;
rb.Enabled = false;
}
catch
{}
try
{
DropDownList ddl= (DropDownList)c;
ddl.Enabled = false;
}
catch
{}
try
{
CheckBox chk = (CheckBox)c;
chk.Enabled = false;
}
catch
{}
try
{
DisableControls(c.Controls);
}
catch{}
}
}

No comments: