【问题标题】:ASP.NET - Accesing the controls in child pageASP.NET - 访问子页面中的控件
【发布时间】:2012-04-10 10:15:15
【问题描述】:

我有一个母版页,那里只有一个菜单项和一个内容占位符。我有另一个继承自此母版页的 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 的计数时,我只看到一个控件,它是表单母版页的菜单项。我应该如何获取当前表单中的控件列表?

【问题讨论】:

    标签: asp.net controls master-pages


    【解决方案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控件。

    【讨论】:

      【解决方案2】:

      这是对我有用的代码。您是对的,无法从页面访问内容控件,因此您使用 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;
          }
      }
      

      【讨论】:

      • 我如何获得内容控制?如果是内容内容 =(Content)Page.FindControl("ContentMain");然后返回 null。
      • 你不能直呼它的名字吗?如果它被称为 ContentMain 那将是 ContentMain.Controls
      • 但是当我输入 ContentMain 时,它不会出现在智能感知菜单中。
      猜你喜欢
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      • 2011-02-28
      • 1970-01-01
      相关资源
      最近更新 更多