开发者

Problem accessing usercontrol in different contentplaceholder from another usercontrol

Now I know this does not make for good design practice, however it is legacy code with a bug that needs fixing so I am going to have to live with it.

The scenario is I have a set of nest Master pages (3 deep), call them Base > Template > 2Col. I am working at the 2Col level. As the name suggests the 2Col master page has two content placeholders, MainContent and SideContent.

I have user UserControl in MainContent that needs to reference another UserControl in SideContent.

ContentPlaceHolder ph = (ContentPlaceHolder)this.Page.Master.FindControl("SideContent");
MyUserControl uc = (MyUserControl )ph.FindControl("MyUserControl1");

I am not sure why this doesn't work, the intellisense when I debug would lead me to think that the ContentPlaceHolder is there, but the first line always returns null?

开发者_如何学Go

Thanks in advance!


Because of the nesting of Master pages you need access the correct master page like so:

ContentPlaceHolder ph = (ContentPlaceHolder)Parent.Parent.FindControl("SideContent");

Alternatively if you need to find any control on the Page from the Master use the following:

ContentPlaceHolder ph = (ContentPlaceHolder)FindControl(Page.Master, "SideContent");

...

private Control FindControl(Control parent, string id)
{
    foreach (Control child in parent.Controls)
    {
        string childId = string.Empty;
        if (child.ID != null)
        {
            childId = child.ID;
        }

        if (childId.ToLower() == id.ToLower())
        {
            return child;
        }
        else
        {
            if (child.HasControls())
            {
                Control response = FindControl(child, id);
                if (response != null)
                    return response;
            }
        }
    }

    return null;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜