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, EventArg开发者_开发技巧s e)
{
}
}
How do I reference the public SqlConnection
cnx
property from an aspx.cs
file that uses this master page?
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;
You have a couple of options:
- cast the
Master
property to yourMasterPage
type and proceed from there. - Include
<%@ MasterType virtualpath="~/path/to/master.master" %>
in your aspx file which will strongly type the Master property.
You should declare an interface IMyMasterPage
and put the property there. Allow your master page to implement it.
Then you can do this on your page.
var myMasterPage = this.MasterPage as IMyMasterPage
精彩评论