Sunday, April 10, 2011

Problem: How to access master page controls from content page in ASP.NET

Impact: You cannot change the text of textbor or label in your master page. There are situations when you want to do that according to the page viewed by the user.

Solution: The solution to this problem is very simple. All you have to do is to create a public property to get and set the text of a textbox in the master page(.cs file). Then you can access this public property from any content page.

Example:

<%-- Copy and paste this line in you contentPage.aspx and change the value of virtualPath attribute according to you master page's name --%>
<%@ MasterType  virtualPath = "~/MasterPage.master" %>

//Create this public property in the masterpage.cs file
public String Textbox1
{
        get { return txtTextbox1.Text; }
        set { txtTextbox1.Text = value; }
}

//In the content page's code behind use these lines of code
Master.Textbox1 = "Arshdeep Virdi";
string myName = Master.Textbox1;

No comments:

Post a Comment