February 18, 2009

Access ASP.NET Master Page controls from Content Page




Mentioned here are two ways you can access MasterPage 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";




'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Access ASP.NET Master Page controls from Content Page"
  1. Lic. Enel R. Almonte said...
    December 21, 2011 12:03 PM

    I Tried to do the Aproach 2 in Visual studio 2010 and it did not worket.

    How it works in 2010?

  2. Anonymous said...
    March 21, 2012 4:24 AM

    Approach 2 also requires the line:

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

    at the top of your content page.

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions