Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access Master page in class file in C#

I have got the following contents in Master 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 have created the following method in this class to disable controls on the Master Page:

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

I am getting the following error on Using "Master" word.

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

like image 629
user3202862 Avatar asked Dec 02 '22 20:12

user3202862


2 Answers

Try this :

var pageHandler = HttpContext.Current.CurrentHandler;
if (pageHandler  is  System.Web.UI.Page)
{
  ((System.Web.UI.Page)pageHandler).Master.FindControl("...").Visible=false;
}
like image 160
Royi Namir Avatar answered Dec 05 '22 11:12

Royi Namir


In your aspx file add the following directive:

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

Create a method exposing your method in the MasterPage:

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

And in your aspx.cs file you can simple:

this.Master.disablecontrol();

Edit: It will change your aspx.designer file making the cast for you in the this.Master property as following:

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

More about MasterType.

like image 23
Vitor Canova Avatar answered Dec 05 '22 10:12

Vitor Canova