Apr 13 2006

Handle MasterPages' Control Events in Content Page

Category: ASP.NET 2.0 - GeneralBil@l @ 06:42

Hi:

While working on a project having MasterPages, Content Pages, TreeView Controls, Themes, etc ... I was faced with the following situation:

In one of the master pages in my application, I had a TreeView, and a custom menu, in a sense, once a button is clicked in that menu, two things shall happen:

  • Redirect to another page
  • Populate the TreeView based on the page we are in now.

Redirecting is pretty simple, however populating the TreeView is not that simple, knowing that the TreeView is placed inside the Master Page.

Solution?

A simple solution would be to override the OnInit() method (in my base class of the application), get the TreeView control from the master page and then populate that TreeView or add any handler for its predefined events as follows:

protected override void OnInit(EventArgs e)
    {
        _tr = (TreeView)Master.FindControl("tvMainNavigation");

        if (_tr != null)
        {
            _tr.TreeNodePopulate += new TreeNodeEventHandler(_tr_TreeNodePopulate);
        }

        // Call Base OnInit()
        base.OnInit(e);
    }

First of all, I am finding the control inside the Master Page, then I am defining an event handler for the TreeNodePopulate event.

Then, in the OnPreRender method I add the following to populate the TreeView:

protected override void OnPreRender(EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (_tr != null)
            {
                PopulateRootLevel();
            }
        }

        // Call based Load methods
        base.OnPreRender(e);
    }

Why OnPreRender? I had to pass in some values in the Page_Load of each content page before populating the TreeView in the base class, that is why I figured out that the best place to populate the TreeView is in the OnPreRender of the base class.

In addition, as you saw above, you can handle any event for the TreeView found in themaster Page:

  • Get the control from the master page
  • In the OnInit() method, attach any event handler to be fired in the content page for that control in the master page.

Hope this helps,

Regards

Tags:

Comments are closed