Saturday, July 11, 2009

Disable All Controls – Using Recursion

I came across a requirement of disabling all the controls on the screen based on some condition. Here’s how I did it.

Disabling all controls on a page may not be as simple as looping through all controls and disabling them, but you also need to consider the child controls of those controls. For instance, if you get the list of controls on your page, mostly what you get is list of divs or panels. So you need to loop through those divs and panels to get hold of actual controls to be disabled. To achieve this we will use recursion here.
You can use the method below to disable all controls. If you are using a master page, you can have this method on your master page or any common class. You can specify all the types of controls



#region DisableAllControls
/// <summary>
/// This method will recursively check all the controls for
/// child controls and disable all the child controls.
/// </summary>
/// <param name="controls"></param>
public static void DisableAllControls(ControlCollection
controlCollection)
{
foreach (Control control in controlCollection)
{
if (control.Controls.Count > 0 && !(control is GridView)
&& !(control is Repeater) && !(control is CheckBoxList))
{
DisableAllControls(control.Controls);
}
else
{
switch (control.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
((TextBox)control).Enabled = false;
break;
case "System.Web.UI.WebControls.DropDownList":
((DropDownList)control).Enabled = false;
break;
case "System.Web.UI.WebControls.CheckBox":
((CheckBox)control).Enabled = false;
break;
case "System.Web.UI.WebControls.DataList":
((DataList)control).Enabled = false;
break;
case "System.Web.UI.WebControls.RadioButtonList":
((RadioButtonList)control).Enabled = false;
break;
case "System.Web.UI.WebControls.Button":
string buttonText = ((Button)control).Text;
//Disable button if its not Next, Previous
if (buttonText.IndexOf("Next") == -1
&& buttonText.IndexOf("Previous") == -1)
{
((Button)control).Enabled = false;
}
break;
default:
break;
}
}
}
}
#endregion


Disabling ALL Repeater/GridView Items

You can modify same method to disable Repeater (or GridView) items.

 
case "System.Web.UI.WebControls.Repeater":
Repeater rpObj = ((Repeater)control);

foreach (RepeaterItem rptrItem in rpObj.Items)
{
if (rptrItem.ItemType == ListItemType.Item
|| rptrItem.ItemType == ListItemType.AlternatingItem)
{
DisableAllControls(rptrItem.Controls);
}
}
break;


Calling this method from a page

If you are calling this method from an ASP.NET page with master page. Use the code below:

 
DisableAllControls(((ContentPlaceHolder)this.Master.FindControl
("ContentPlaceHolder1")).Controls);

Or condition can be placed directly in Master Page:

DisableAllControls(ContentPlaceHolder1.Controls);

1 comment: