2009-02-02 30 views
17

Tengo una lista desplegable múltiple en una página y me gustaría deshabilitar todo si el usuario selecciona una casilla de verificación que dice deshabilitar todo. Hasta ahora tengo este código y no está funcionando. ¿Alguna sugerencia?¿Cómo desactivo todos los controles en la página ASP.NET?

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

Respuesta

37

Cada control tiene controles secundarios, por lo que había necesidad de utilizar la recursividad para llegar a todos ellos:

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

     DisableControls(c, State); 
    } 
} 

Entonces lo llaman así:

protected void Event_Name(...) { 
    DisableControls(Page,false); // use whatever top-most control has all the dropdowns or just the page control 
} // divs, tables etc. can be called through adding runat="server" property 
+0

¡Gracias! Quería desactivar todos los botones/cuadros de texto/cuadros combinados en un formulario a excepción de uno, y deshabilitar un panel deshabilita todos los controles para que no funcione. Usando su método, pude apagar solo los controles que quería, pero no los paneles. – ajs410

18

Sería más fácil si se pone todos los controles que desea desactivar en un panel y luego simplemente activar/desactivar el panel.

1

Tienes que hacer esto recursiva, Quiero decir que tiene que deshabilitar los controles secundarios de controles para:

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; 
     } 
    } 
} 
1

Aquí hay una versión de VB.NET que también toma una opción parámetro ional para que también se pueda usar para habilitar los controles.

privadas SetControls Sub (ByVal parentControl Como control, opcional ByVal permitir 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 
0

Si realmente desea desactivar todos controles en una página, entonces la manera más fácil de hacer esto es para establecer la propiedad Deshabilitado del formulario en verdadero.

ASPX:

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

de código subyacente:

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

Pero, por supuesto, esto también se desactive su casilla de verificación, por lo que no será capaz de hacer clic en la casilla para volver a habilitar los controles.

8

Deja un panel alrededor de la parte de la página que desea discapacitados:

< asp:Panel ID="pnlPage" runat="server" > 
     ... 
    </asp:Panel> 

Dentro de Load:

If Not Me.Page.IsPostBack Then 
     Me.pnlPage.Enabled = False 
    End If 

... o el equivalente C#. : o)

1
private void ControlStateSwitch(bool state) 
{ 
    foreach (var x in from Control c in Page.Controls from Control x in c.Controls select x) 
     if (ctrl is ASPxTextBox) 

      ((ASPxTextBox)x).Enabled = status; 

     else if (x is ASPxDateEdit) 

      ((ASPxDateEdit)x).Enabled = status; 
} 

Utilizo un enfoque lineal. Al utilizar devExpress debe incluir DevExpress.Web.ASPxEditors lib.

28

Sé que esta es una publicación anterior, pero así es como acabo de resolver este problema. AS por el título "¿Cómo desactivo todos los controles en la página ASP.NET?" Usé Reflection para lograr esto; funcionará en todos los tipos de control que tengan una propiedad habilitada. Simplemente llame a DisableControls pasando el control padre (es decir, Formulario).

C#:

private void DisableControls(System.Web.UI.Control control) 
{ 
    foreach (System.Web.UI.Control c in control.Controls) 
    { 
     // Get the Enabled property by reflection. 
     Type type = c.GetType(); 
     PropertyInfo prop = type.GetProperty("Enabled"); 

     // Set it to False to disable the control. 
     if (prop != null) 
     { 
      prop.SetValue(c, false, null); 
     } 

     // Recurse into child controls. 
     if (c.Controls.Count > 0) 
     { 
      this.DisableControls(c); 
     } 
    } 
} 

VB:

Private Sub DisableControls(control As System.Web.UI.Control) 

     For Each c As System.Web.UI.Control In control.Controls 

      ' Get the Enabled property by reflection. 
      Dim type As Type = c.GetType 
      Dim prop As PropertyInfo = type.GetProperty("Enabled") 

      ' Set it to False to disable the control. 
      If Not prop Is Nothing Then 
       prop.SetValue(c, False, Nothing) 
      End If 

      ' Recurse into child controls. 
      If c.Controls.Count > 0 Then 
       Me.DisableControls(c) 
      End If 

     Next 

    End Sub 
+2

Esta es la mejor solución porque deshabilita cualquier control que tenga la propiedad "Habilitado". Mi proyecto actual puede tener una variedad de controles personalizados dentro de un cierto fieldset, era feo solo desactivar ciertos tipos conocidos. – ASalazar

+1

¡Perfecto para mí! Gracias. – MAW74656

2

estaba trabajando con controles ASP.NET y HTML me ha gustado esta

public void DisableForm(ControlCollection ctrls) 
    { 
     foreach (Control ctrl in ctrls) 
     { 
      if (ctrl is TextBox) 
       ((TextBox)ctrl).Enabled = false; 
      if (ctrl is Button) 
       ((Button)ctrl).Enabled = false; 
      else if (ctrl is DropDownList) 
       ((DropDownList)ctrl).Enabled = false; 
      else if (ctrl is CheckBox) 
       ((CheckBox)ctrl).Enabled = false; 
      else if (ctrl is RadioButton) 
       ((RadioButton)ctrl).Enabled = false; 
      else if (ctrl is HtmlInputButton) 
       ((HtmlInputButton)ctrl).Disabled = true; 
      else if (ctrl is HtmlInputText) 
       ((HtmlInputText)ctrl).Disabled = true; 
      else if (ctrl is HtmlSelect) 
       ((HtmlSelect)ctrl).Disabled = true; 
      else if (ctrl is HtmlInputCheckBox) 
       ((HtmlInputCheckBox)ctrl).Disabled = true; 
      else if (ctrl is HtmlInputRadioButton) 
       ((HtmlInputRadioButton)ctrl).Disabled = true; 

      DisableForm(ctrl.Controls); 
     } 
    } 

llamado así

DisableForm(Page.Controls); 
Cuestiones relacionadas