Selectively disabling WebControl elements
- by NeilD
I have an ASP.Net MasterPage with a PlaceHolder element.
The contents of the PlaceHolder can be viewed in two modes: read-write, and read-only.
To implement read only, I wanted to disable all inputs inside the PlaceHolder.
I decided to do this by recursively looping through the controls collection of the PlaceHolder, finding all the ones which inherit from WebControl, and setting control.Enabled = false;.
Here's what I originally wrote:
private void DisableControls(Control c)
{
if (c.GetType().IsSubclassOf(typeof(WebControl)))
{
WebControl wc = c as WebControl;
wc.Enabled = false;
}
//Also disable all child controls.
foreach (Control child in c.Controls)
{
DisableControls(child);
}
}
This worked fine, and all controls are disabled... But then the requirement changed ;)
NOW, we want to disable all controls except ones which have a certain CssClass.
So, my first attempt at the new version:
private void DisableControls(Control c)
{
if (c.GetType().IsSubclassOf(typeof(WebControl)))
{
WebControl wc = c as WebControl;
if (!wc.CssClass.ToLower().Contains("someclass"))
wc.Enabled = false;
}
//Also disable all child controls.
foreach (Control child in c.Controls)
{
DisableControls(child);
}
}
Now I've hit a problem. If I have (for example) an <ASP:Panel> which contains an <ASP:DropDownList>, and I want to keep the DropDownList enabled, then this isn't working.
I call DisableControls on the Panel, and it gets disabled. It then loops through the children, and calls DisableControls on the DropDownList, and leaves it enabled (as intended). However, because the Panel is disabled, when the page renders, everything inside the <div> tag is disabled!
Can you think of a way round this? I've thought about changing c.GetType().IsSubclassOf(typeof(WebControl)) to c.GetType().IsSubclassOf(typeof(SomeParentClassThatAllInputElementsInheritFrom)), but I can't find anything appropriate!