How do I disable all controls in ASP.NET page?

后端 未结 9 1672
旧时难觅i
旧时难觅i 2020-12-14 08:17

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 s

9条回答
  •  情书的邮戳
    2020-12-14 08:56

    I know this is an old post but this is how I have just solved this problem. AS per the title "How do I disable all controls in ASP.NET page?" I used Reflection to achieve this; it will work on all control types which have an Enabled property. Simply call DisableControls passing in the parent control (I.e., Form).

    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
    

提交回复
热议问题