2012-04-10 72 views
0

我有一个母版页,那里只有一个菜单项和一个contentplaceholder。我有另一个Web窗体继承形式这个母版页。不过,我已将所有控件放在contentplaceholder中。在我的表单的Page_Load事件中,我想设置所有下拉列表控件的Enabled = false。为此我写:ASP.NET - 访问子页面中的控件

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

但所有的下拉列表仍保持启用。当我检查Page.Control的计数时,我只看到一个控件,它是窗体主页面的菜单项。我应该怎么做才能获得当前形式的控件列表?

回答

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控制。

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; 
    } 
} 
+0

如何获得内容控制?如果是Content content =(Content)Page.FindControl(“ContentMain”);那么这将返回null。 – 2012-04-10 10:18:04

+0

你不能用它的名字来称呼它吗?如果它被称为ContentMain,它将是ContentMain.Controls – Eugene 2012-04-10 10:18:58

+0

,但是当我键入ContentMain时,它不会显示在intellisense菜单中。 – 2012-04-10 10:21:14