Wednesday, June 6, 2012

Handling Master Page's Control event in Child Page

One of the favourite query in interviews is how to handle the event of a control which is in Master Page from the child page.
We will see in the following simple steps how to do that.
Step 1. Create a new website using VS.
Step 2. Create a master page with following content.


<body>
    <form id="form1" runat="server">
    <div style="height:50px; background-color:Yellow;">Header
    <br />
        <asp:RadioButtonList ID="RadioButtonList1" runat="server"
            RepeatDirection="Horizontal" AutoPostBack="True"
            onselectedindexchanged="RadioButtonList1_SelectedIndexChanged">
            <asp:ListItem>Video</asp:ListItem>
            <asp:ListItem>Text</asp:ListItem>
            <asp:ListItem>Audio</asp:ListItem>
        </asp:RadioButtonList>
    </div>
    <div >
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
        dsf
        </asp:ContentPlaceHolder>
    </div>
    <div style="height:20px; background-color:blue;">Footer</div>
    </form>
</body>

What we have done here : We have taken a control in master page that is a radio button list.

Step 3. Get the selected index change event of Radiobutton list and you will see that it is in master page.
as shown here..



protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }


but we want to call it from child page right!

Step 4. Create a child page with the master page selected.

Now both the master page and child page in place lets move further..

Step 5. In order to expose any control of master page to child pages we need to  expose it as public property of the master page. So in code behind of master page create a public property which will expose the radio button list control to child pages.



public  RadioButtonList ContentList
    {
        get { return RadioButtonList1; }

    }

Step 6. Go to the childpage.aspx and set the following directive, without which that public property would not be available in child page.

<%@ MasterType VirtualPath="~/DefaultMaster.master" %>

Step 7. In code behind of child.aspx create an event handler that will handle the event of radio button list.



protected void ContentList_SelectedIndexChanged(object sender, EventArgs e)
    {
       
    }

Step 8. So we have an event handler now in child page which will be called when the radio button list control in master page is clicked. As a final step we need to assign this event to the radiobuttonlist.selectedeventchanges event in page load as follows:


protected void Page_Load(object sender, EventArgs e)
    {
          this.Master.ContentList.SelectedIndexChanged += new EventHandler(ContentList_SelectedIndexChanged);
       
    }

Step 8. Put a breakpoint in the ContentList_SelectedIndexChanged and see when you click the radiobuttonlist in master page this event of child page is being called.

Hope this helped!

No comments:

Post a Comment