Aaron Li's Blog

Write it down before I forget

  Home  |   Contact  |   Syndication    |   Login
  30 Posts | 0 Stories | 21 Comments | 1 Trackbacks

News

Google

Archives

Other's Idea

When a page is using a master page, and that master page is using another master page, and so on, then how to find a control on the page?

For example, my pages could have three-level master pages. Let's call the third-level master page Master3, which contains a ContentPlaceHolder called PlaceHolder3; Master3's master page is Master2, which contains PlaceHolder2; and Master1, PlaceHolder1. I want to find the panel "pnlTest" on the content page.

Here is my function.

    public bool FindPageControl()
    {
        System.Web.UI.Page oPage = HttpContext.Current.Handler as System.Web.UI.Page;
        System.Web.UI.MasterPage oMasterPage = null;
        System.Web.UI.WebControls.ContentPlaceHolder oPlaceHolder = null;
        System.Web.UI.WebControls.Panel oPnlTest = null;
        if (oPage.Master.Master != null)
        {
            if (oPage.Master.Master.Master != null)
            {
                oMasterPage = (System.Web.UI.MasterPage)oPage.Master.Master.Master;
                oPlaceHolder = (System.Web.UI.WebControls.ContentPlaceHolder)oMasterPage.FindControl("PlaceHolder1").FindControl("PlaceHolder2").FindControl("PlaceHolder3"); //to make the logic strict, better find the control step by step
            }
            else
            {
                oMasterPage = (System.Web.UI.MasterPage)oPage.Master.Master;
                oPlaceHolder = (System.Web.UI.WebControls.ContentPlaceHolder)oMasterPage.FindControl("PlaceHolder1").FindControl("PlaceHolder2");
            }
        }
        else
        {
            oMasterPage = (System.Web.UI.MasterPage)oPage.Master;
            if (oMasterPage != null)
                oPlaceHolder = (System.Web.UI.WebControls.ContentPlaceHolder)oMasterPage.FindControl("PlaceHolder1");
        }

        if (oPlaceHolder != null)
            oPnlTest = (System.Web.UI.WebControls.Panel)oPlaceHolder.FindControl("pnlTest");
        else
            oPnlTest = (System.Web.UI.WebControls.Panel)oPage.FindControl("pnlTest");

        if (oPnlTest != null)
            return true;

        return false;
    }

By this example, it is not difficult to figure out how to find a control on any level master page or content page.
posted on Wednesday, February 13, 2008 12:33 PM

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: