Mikayil Abdullayev
Mikayil Abdullayev

Reputation: 12367

ASP.NET - Accesing the controls in child page

I have a master page, there's only one menu item and a contentplaceholder there. I have another web form that inherits form this master page. As nor mal I've put all my controls in the contentplaceholder. On my form's Page_Load event I want to set Enabled=false of all the dropdownlist controls. For this purpose I write:

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

But all the dropdownlists remain Enabled. When I check for the count of the Page.Control I see only one control and it's the menuitem of the form's masterpage. What should I do to get the list of controls that are in my current form?

Upvotes: 0

Views: 739

Answers (2)

Eugene
Eugene

Reputation: 2985

Here is the code that worked for me. You are correct, the content control is not accessible from the page, so you use the Master.FindControl... code. Just be sure to plug in the ContentPlaceHolderID argument into the Master.FindControl("righthere") expression.

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

Upvotes: 1

Imran Rizvi
Imran Rizvi

Reputation: 7438

your foreach loop will not work as your control can have child control and they can also have child control and then DDL.

What I'll prefer is to create a list of controls first then iterate through that list which is filled with your desire DDL controls.

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);
       }
     }
  }  
}

Later you can directly loop through foundSofar and it is sure that it will contain all DDL controls inside it.

Upvotes: 1

Related Questions