Accessing the main page in a class file in C #

I have the following content on the main page:

<ul>
    <li id="link1" runat="server"><a href="mytestfile.aspx">Test Files</a></li>
    <li id="link2" runat="server"><a href="mylistitemtest.aspx">List Item Test</a></li>
    <li id="link3" runat="server"><a href="Mytest2.aspx">Some Test</a></li>    
</ul> 

I have a class called data_class.cs, and I created the following method in this class to disable controls on the main page:

public static void disablecontrol()
{
    Master.FindControl("link1").Visible = false;
    Master.FindControl("Link3").Visible = false;
}

I get the following error when using the word "Master".

an object reference is Required for non-staticfield, method, property 'System.Web.UI.MasterPage.master.get'

+4
source share
3 answers

Try the following:

var pageHandler = HttpContext.Current.CurrentHandler;
if (pageHandler  is  System.Web.UI.Page)
{
  ((System.Web.UI.Page)pageHandler).Master.FindControl("...").Visible=false;
}
+12
source

In your file aspxadd the following directive:

<%@ MasterType TypeName="YorNamespace.YourMasterClass" %>

Create a method that exposes your method to MasterPage:

public void disablecontrol()
{
    Master.Link1.Visible = false;
    Master.Link3.Visible = false;
}

And in your file aspx.csyou can simply:

this.Master.disablecontrol();

: aspx.designer, this.Master :

/// <summary>
/// Master property.
/// </summary>
/// <remarks>
/// Auto-generated property.
/// </remarks>
public new YorNamespace.YourMasterClass Master {
    get {
        return ((YorNamespace.YourMasterClass)(base.Master));
    }
}

MasterType.

+2

Since this method is static, it does not have access to the properties of the page object . Run this code in the page instance method.

+1
source

All Articles