开发者

Menu control in Child master page cannot be accessed in content page in nested master page scenario

开发者 https://www.devze.com 2022-12-20 04:41 出处:网络
I have a nested master page scenario where I have a menu both in main master and in the child master page. Now if I try to access either of the two... both are not accessible in the content page. I am

I have a nested master page scenario where I have a menu both in main master and in the child master page. Now if I try to access either of the two... both are not accessible in the content page. I am using开发者_如何学Go this code to access it. The variable n is getting null value.

Menu n = (Menu)this.Master.FindControl("Menu1");


Is your Menu control at the root level in this.Master? FindControl isn't recursive, so if your Menu is nested inside of another control (a Panel, etc.) then FindControl will return null.

You can write your own recursive version of FindControl, which is what I did on a previous project. This is off the top of my head (I don't have the code in front of me):

public static Control RecursiveFindControl(ControlCollection cc, String id) {
    Control c = cc.FindControl(id);

    if (c == null) {
        foreach (Control child in cc) {
            if (child.HasChildren) {
                return RecursiveFindControl(child.Controls, id);
            }
        }
    }

    return c;
}

Call it this way:

Menu foo = (Menu)RecursiveFindControl(this.Master.Controls, "menu");
0

精彩评论

暂无评论...
验证码 换一张
取 消