首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何禁用ASP.NET页面中的所有控件?

如何禁用ASP.NET页面中的所有控件?
EN

Stack Overflow用户
提问于 2009-02-02 23:01:13
回答 8查看 78.8K关注 0票数 21

我有多个下拉列表在一个页面上,并想禁用所有,如果用户选择了一个复选框,这是禁用所有。到目前为止,我有这段代码,但它不能工作。有什么建议吗?

代码语言:javascript
复制
foreach (Control c in this.Page.Controls)
{
    if (c is DropDownList)
        ((DropDownList)(c)).Enabled = false;
}
EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2009-02-02 23:10:44

每个控件都有子控件,因此您需要使用递归来访问所有控件:

代码语言:javascript
复制
protected void DisableControls(Control parent, bool State) {
    foreach(Control c in parent.Controls) {
        if (c is DropDownList) {
            ((DropDownList)(c)).Enabled = State;
        }

        DisableControls(c, State);
    }
}

然后这样叫它:

代码语言:javascript
复制
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
票数 39
EN

Stack Overflow用户

发布于 2013-04-09 23:15:49

我知道这是一个古老的帖子,但这是我刚刚解决这个问题的方法。按照标题“如何禁用ASP.NET页中的所有控件?”我使用反射来实现这一点;它将在所有具有Enabled属性的控件类型上工作。只需调用传入父控件(即表单)的DisableControls即可。

C#:

代码语言:javascript
复制
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:

代码语言:javascript
复制
    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
票数 32
EN

Stack Overflow用户

发布于 2009-02-02 23:04:22

如果您将所有要禁用的控件放在一个面板中,然后只启用/禁用该面板,这将是最简单的。

票数 19
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/505353

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档