Search code examples
asp.netinheritancemaster-pages

Reference a MasterPage property


I have a master page with the following code:

public partial class MasterPage : System.Web.UI.MasterPage
{
    public SqlConnection cnx;
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
}

How do I reference the public SqlConnection cnx property from an aspx.cs file that uses this master page?


Solution

  • In your master page:

        public SqlConnection CnxInMasterPage
        {
            get { return this.cnx; }
        }
    

    In Content page (first add using so you can reference 'MasterPage' type)

    var cnx = ((MasterPage)Master).CnxInMasterPage;