Access master page control in content page using asp.net C#



Often developers need to access the controls of master pages for fulfill their requirement. Let me give you an example. 

Example:
We have a one Language dropdown in master page and we want to change the language of the matter inside the content page by changing Language dropdown.

Now let’s start
Open visual studio and go to File and click Web Site
Access master page control in content page using asp.net C# 1

Select ASP.NET web site and click OK
Access master page control in content page using asp.net C# 2


Go to Site.Master page file
Access master page control in content page using asp.net C# 3

In Site.Master page add the following code for dropdown.


<asp:Label ID="lblLanguage" runat="server" Text="SelectLanguage" ForeColor="White"></asp:Label>&nbsp;
<asp:DropDownList ID="ddlLanguages" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlLanguages_SelectedIndexChanged" Width="100px">
<asp:ListItem Selected="True" Value="You select English">English</asp:ListItem>
<asp:ListItem Value="You select French">French</asp:ListItem>
</asp:DropDownList>

Access master page control in content page using asp.net C# 4
 
Inside your Site.Master.cs file create public property called Language.
public String Language
{
        get
        {
            return (String)ddlLanguages.SelectedValue;
        }
        set
        {
            ddlLanguages.SelectedValue = value;
        }
}

Set the property value inside the dropdown selected event changed.

protected void ddlLanguages_SelectedIndexChanged(object sender, EventArgs e)
{
        Language = ddlLanguages.SelectedValue;
}

Access master page control in content page using asp.net C# 5


Now go to Default.aspx page.
Access master page control in content page using asp.net C# 6


Now you can see the Default.aspx page.
Access master page control in content page using asp.net C# 7

Microsoft Visual Studio.net generates the default code for you; now remove the default code for simplicity. Just below the page directive add the following lines so that we are able to access the master page properties.

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

Inside the content place holder add Label so that we can view result by using this label 
 
<br />
    <asp:Label ID="lblContent" runat="server"></asp:Label>
<br />
 
Access master page control in content page using asp.net C# 7



Now inside your Default.aspx.cs file write the following lines.

lblContent.Text = Master.Language;
Access master page control in content page using asp.net C# 8

Run the project and change the language dropdown and view the result. 
Access master page control in content page using asp.net C# 9




Now you can change this code according to your requirement.
That’s it.
Hope this help. :)