I’m a beginner at ASP.net, and want to create a class file that contains common used methods across my application. Like the one here that hides certain ButtonLink‘s in the login.aspx and registration.aspx pages.
But when i start either one of these pages i get this error :
Object reference not set to an instance of an object.
Here’s my code :
Helper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public class Helper : System.Web.UI.Page
{
public void hideLinks(){
// error is produced at the following line at the start of
// login.aspx or registration.aspx pages.
LinkButton profile = (LinkButton)Master.FindControl("LinkButton1");
LinkButton logout = (LinkButton)Master.FindControl("LinkButton2");
profile.Visible = false;
logout.Visible = false;
}
}
}
login.aspx.cs & registration.aspx.cs:
void Page_PreInit(object sender, EventArgs e)
{
//LinkButton profile = (LinkButton)Master.FindControl("LinkButton1");
//LinkButton logout = (LinkButton)Master.FindControl("LinkButton2");
//profile.Visible = false;
//logout.Visible = false;
Helper master_helper = new Helper();
master_helper.hideLinks();
}
Instantiating a new
Helper(that is, a newSystem.Web.UI.Page) doesn’t exist as part of the full page request so it doesn’t have a reference to the sameMaster(if it even has one at all). Instead, redesign yourHelperto take aMaster(or thePage) in:Then your usage might look like:
You could also redesign the method to be static and simply pass in the
Page(orMaster) reference in with thehideLinksmethod as an argument, but this is up to you.