views:

3202

answers:

5

I have multiple dropdownlist in a page and would like to disable all if user selects a checkbox which reads disable all. So far I have this code and it is not working. Any suggestions?

foreach (Control c in this.Page.Controls)
{
    if (c is DropDownList)
        ((DropDownList)(c)).Enabled = false;
}
+5  A: 

It would be easiest if you put all the controls you want to disable in a panel and then just enable/disable the panel.

bechbd
+7  A: 

Each control has child controls, so you'd need to use recursion to reach them all:

protected void DisableControls(Control parent) {
    foreach(Control c in parent.Controls) {
        if (c is DropDownList) {
            ((DropDownList)(c)).Enabled = false;
        }

        DisableControls(c);
    }
}

Then call it like so:

protected void Event_Name(...) {
    DisableControls(Page); // use whatever top-most control has all the dropdowns or just the page control
}
John Sheehan
Thanks! I wanted to turn off all the buttons/textboxes/comboboxes on a form except for one, and disabling a panel disables all the controls so it won't work. Using your method, I could turn off just the controls I wanted, but not the panels.
ajs410
A: 

You have to do this recursive, I mean you have to disable child controls of controls to :

protected void Page_Load(object sender, EventArgs e)
{
  DisableChilds(this.Page);
}

private void DisableChilds(Control ctrl)
{
   foreach (Control c in ctrl.Controls)
   {
      DisableChilds(c);
      if (c is DropDownList)
      {
           ((DropDownList)(c)).Enabled = false;
      }
    }
}
Canavar
A: 

Here's a VB.NET version which also takes an optional parameter so it can be used for enabling the controls as well.

Private Sub SetControls(ByVal parentControl As Control, Optional ByVal enable As Boolean = False)

    For Each c As Control In parentControl.Controls
        If TypeOf (c) Is CheckBox Then
            CType(c, CheckBox).Enabled = enable
        ElseIf TypeOf (c) Is RadioButtonList Then
            CType(c, RadioButtonList).Enabled = enable
        End If
        SetControls(c)
    Next

End Sub
A: 

If you really want to disable all controls on a page, then the easiest way to do this is to set the form's Disabled property to true.

ASPX:

<body>
    <form id="form1" runat="server">
      ...
    </form>
</body>

Code-behind:

protected void Page_Load(object sender, EventArgs e)
{
 form1.Disabled = true;
}

But of course, this will also disable your checkbox, so you won't be able to click the checkbox to re-enable the controls.

M4N