Tuesday 7 August 2012

Access ASP.NET Master Page controls from Content Page

Approach 1

Go to the Content page (Default.aspx) and add the following line below the <Page> directive to register the MasterPage


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


Now in the code behind of ContentPage, access the MasterPage control in the following manner

C#


TextBox tb = (TextBox)Master.FindControl("txtMaster");

tb.Text = "Something";


VB.NET


        Dim tb As TextBox = CType(Master.FindControl("txtMaster"), TextBox)

        tb.Text = "Something"



Approach 2

Expose the Text property of the TextBox control in the MasterPage and use get set properties as shown below

C#


public string SomeText

{

    get

    {

        return txtMaster.Text;

    }

    set

    {

        txtMaster.Text = value;

    }



}



VB.NET


    Public Property SomeText() As String

        Get

            Return txtMaster.Text

        End Get

        Set(ByVal value As String)

            txtMaster.Text = value

        End Set



    End Property


Now accessing the Text property from the Content page is as simple as this line of code. Add the code in the codebehind of the MasterPage


Master.SomeText = "Something";

0 comments:

Post a Comment


                                                            
 
Design by Abhinav Ranjan Sinha