HighestPie
HighestPie

Reputation: 151

ASP.NET Accessing controls from a MasterPage using only an instance of it

I have a set of three MasterPages with different filters on them consisting of dropdownlists. When the page inits I want to fill these dropdowns with options using a helping class in the App_Code folder to decrease repeated code. The problem I have is that I cannot find these dropdowns in the MasterPage the method below receives. Can this be done or should I explore other options?

I have tried to first find the ContentPlaceHolder and then searching but cannot find the ContentPlaceHolder the dropdowns are in.
I have also tried to access the parent and from there find the ContentPlaceHolder but no dice.

Other options being sending the dropdowns to this class and filling them, which is the easier solution. But I want to explore this very general solution first.

public static void FillFilters(MasterPage page) {

    DropDownList[] dropdowns = new DropDownList[3];
    dropdowns[0] = (DropDownList)page.FindControl("StatusDropDown");
    dropdowns[1] = (DropDownList)page.FindControl("DepartmentDropDown");
    dropdowns[2] = (DropDownList)page.FindControl("EmployeeDropDown");
    ...code filling the dropdowns etc. etc.

Upvotes: 2

Views: 62

Answers (2)

HighestPie
HighestPie

Reputation: 151

To add on to Juan answer (maybe this should be an edit?) I decided to use the following in my final code:

public static void FillFilters(MasterPage page) {
    Control parent = page.Controls[0];

    DropDownList[] dropdowns = new DropDownList[3];
    dropdowns[0] = (DropDownList)parent.FindControlRecursive("StatusDropDown");
    dropdowns[1] = (DropDownList)parent.FindControlRecursive("DepartmentDropDown");
    dropdowns[2] = (DropDownList)parent.FindControlRecursive("EmployeeDropDown");

Since I use the MasterPage later in the method.

Upvotes: 0

Juan Ignacio Cornet
Juan Ignacio Cornet

Reputation: 239

Try this extension method. You don't need the MasterPage, just that the control should parent of your current control

public static class ControlsExtensionMethods
{
    public static Control FindControlRecursive(this Control root, string id)
    {
        if (id == string.Empty)
        {
            return null;
        }


        if (root.ID == id)
        {
            return root;
        }

        foreach (Control nestedControl in root.Controls)
        {
            Control foundedControlInNested = FindControlRecursive(nestedControl, id);
            if (foundedControlInNested != null)
            {
                return foundedControlInNested;
            }
        }
        return null;
    }
}

Upvotes: 2

Related Questions