16
votes

Here is my master page file. I need to pass strName, id, url, starttime, etc. to my Child page. I know we can write this logic in our Child page, but, I would like to access this Master Page variable in my Child page only.

I cannot write this logic in each set/get method. While accessing these variable in the Child page, I am getting null values. basically here the master pageload calls after the child pageload calls over:

  1. MASTER PAGE NAME: MyMasterPage

    public partial class MyMasterPage: MasterPage { public string strName = string.Empty; public string id= string.Empty; public string url = string.Empty; public string startTime = string.Empty; public string endTime = string.Empty; public string remoteUrl = string.empty;

      public void Page_Load(object sender, EventArgs e)
      {
    
         DataTable dtEventTable = DataAccessManager.GetEventInfo(Connection);
    
         if (dtEventTable.Rows.Count > 0)
         {
                strName = dtEventTable.Rows[0]["NAME"].ToString(); 
                id = dtEventTable.Rows[0]["ID"].ToString(); 
                url= dtEventTable.Rows[0]["URL"].ToString(); 
                starttime = dtEventTable.Rows[0]["starttime"].ToString(); 
                endtime = dtEventTable.Rows[0]["endtime"].ToString(); 
                remotelive = dtEventTable.Rows[0]["remotelive"].ToString(); 
                // assume that strName = "TCG",id=5, startime=20111001 etc.
         }
     }
    

    }

4

4 Answers

15
votes
4
votes

Found this by Ramesh T on https://forums.asp.net/post/5557778.aspx

U better create a strongly typed reference to ur master page by adding a @ MasterType directive in ur content (aspx page) as shown below

<%@ MasterType  virtualPath="~/MasterPage1.master"%>

and access its members in your aspx page or code behind (aspx.cs) as below

var test1Text = Master.test1;

This way you don't need to cast.

3
votes

This would work, as Muhammad Hasan and Pete suggested:

string name = ((MyMasterPage)this.Master).strName; 

Or:

<%@ MasterType  virtualPath="~/MasterPage1.master"%>
var test1Text = Master.test1; 

however, consider that code inside Page_Load event at master page, is executed after Page_Load in your content page.

So if you set the value of your variable in master page, and then try to get in content page, you will get null value.

you will find here more information: https://msdn.microsoft.com/en-us/library/dct97kc3.aspx

-2
votes

You can use Session[] object for reaching variables from another page.