0

我有一个母版页,那里只有一个菜单项和一个内容占位符。我有另一个继承自此母版页的 Web 表单。正常情况下,我已将所有控件放在 contentplaceholder 中。在我的表单的 Page_Load 事件中,我想设置所有下拉列表控件的 Enabled=false。为此,我写:

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

但是所有下拉列表都保持启用状态。当我检查 Page.Control 的计数时,我只看到一个控件,它是表单母版页的菜单项。我应该怎么做才能获得当前表单中的控件列表?

4

2 回答 2

1

这是对我有用的代码。您是对的,无法从页面访问内容控件,因此您使用 Master.FindControl... 代码。请务必将 ContentPlaceHolderID 参数插入 Master.FindControl("righthere") 表达式。

ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder)Master.FindControl("MainContent");
if(contentPlaceHolder != null)
{
    foreach (Control c in contentPlaceHolder.Controls)
    {
        DropDownList d = c as DropDownList;
        if (d != null)
            d.Enabled = false;
    }
}
于 2012-04-10T10:16:35.867 回答
1

您的 foreach 循环将不起作用,因为您的控件可以有子控件,它们也可以有子控件,然后是 DDL。

我更喜欢首先创建一个控件列表,然后遍历该列表,其中填充了您想要的 DDL 控件。

public void FindTheControls(List<Control> foundSofar, Control parent) 
{
  foreach(var c in parent.Controls) 
  {
    if(c is IControl) //Or whatever that is you checking for 
    {
       if (c is DropDownList){ foundSofar.Add(c); } continue;

       if(c.Controls.Count > 0) 
       {
           this.FindTheControls(foundSofar, c);
       }
     }
  }  
}

稍后你可以直接循环通过foundSofar,它肯定会包含其中的所有DDL控件。

于 2012-04-10T10:22:28.390 回答