I'm trying to access a public class in my MasterPage code file from a child page but cannot get it working. I've tried to use the same method as accessing a public int as follows but the child page doesn't recognise any of the class items.
MasterPage.cs
private int _Section;
public int Section
{
get{return _Section;}
set{_Section = value;}
}
public class HeaderPanel
{
private bool _Visible = true;
public bool Visible
{
get { return _Visible; }
set { _Visible = value; }
}
private string _Theme;
public string Theme
{
get { return _Theme; }
set { _Theme = value; }
}
public HeaderPanel(bool Visible, string Theme)
{
this.Visible = Visible;
this.Theme = Theme;
}
}
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Master.Section = 1; // This works
Master.HeaderPanel.Visible = true; // This doesn't work
Master.HeaderPanel.Theme = "Dark"; // This doesn't work
}
The error message I get is:
'HeaderPanel': cannot reference a type through an expression
Master.Section = 1;
This works because Master
is a property on Default
and that property is an instance of MasterPage
. You are simply setting the Section
value on that instance.
Master.HeaderPanel.Visible = true;
This doesn't work because, while Master
is still the same instance, HeaderPanel
is a type and not an instance of anything. So you're trying to set Visible
statically on that type.
If you meant for it to be static
, make it static
:
private static bool _Visible = true;
public static bool Visible
{
get { return _Visible; }
set { _Visible = value; }
}
And access it via the type and not the instance:
MasterPage.HeaderPanel.Visible = true;
If, on the other hand (and possibly more likely?), you did not mean for it to be static
, then you need an instance of the HeaderPanel
type on a MasterPage
instance. So in MasterPage
you'd create a property for that:
private HeaderPanel _header = new HeaderPanel();
public HeaderPanel Header
{
get { return _header; }
set { _header = value; }
}
Then you could access it through that property:
Master.Header.Visible = true;