Thursday, October 14, 2010

Accessing Master page control values from child page

Accessing Master page control values from child page:

Today, I am discussing about very common requirement where we need to access value of Master page from Child page. We will consider a case where there is dropdownlist in Master page and on change of dropdownlist, we will use selected value of Dropdownlist in child page. Lets start by following below steps:

1. Create Master page and add dropdownlist on aspx page

<asp:DropDownList ID="ddlThemes" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlThemes_OnSelectedIndexChanged">
<asp:ListItem Text="Select Theme" Value="0" Selected="true"></asp:ListItem>
<asp:ListItem Text="Red" Value="Red"></asp:ListItem>
<asp:ListItem Text="Blue" Value="Blue"></asp:ListItem>
<asp:ListItem Text="Green" Value="Green"></asp:ListItem>
</asp:DropDownList>

2. We need to raise an event when dropdownlist is changed. For this create public event and raise event from dropdownlist selectedindex change event in masterpage.cs file

public event CommandEventHandler ThemeChanged;
protected void ddlThemes_OnSelectedIndexChanged(object sender, EventArgs e)
{
    if (ddlThemes.SelectedIndex != 0 && ThemeChanged != null)
        ThemeChanged(this, new CommandEventArgs(ddlThemes.SelectedItem.Text, ddlThemes.SelectedValue));
}

3. Now create child page referring to above master page created. Add below code in aspx file:

<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterPages/masterpage.master" CodeFile="ChildPage.aspx.cs" Inherits="ChildPage" %>
<%@ MasterType VirtualPath="~/MasterPages/masterpage.master" %>

4. Now write the code to handle the event (created in Master page) in child code behind page:
public partial class ChildPage : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        Master.ThemeChanged += new CommandEventHandler(ThemeChangedFromMasterPage);
    }
    private void ThemeChangedFromMasterPage(object sender, CommandEventArgs e)
    {
        string ThemeText = e.CommandName;
        string ThemeValue = e.CommandArgument.ToString();
        Response.Write(ThemeText + " " + ThemeValue);
    }
}

That's all. Above steps will also help you to understand concept of Events and Events Handlers in .Net.

No comments:

Post a Comment