使用方法控制母版页时:对象引用未设置为对象的实例

时间:2012-11-30 16:19:55

标签: c# asp.net class exception master-pages

我是ASP.net的初学者,想要在我的应用程序中创建一个包含常用方法的类文件。就像这里隐藏ButtonLinklogin.aspx页中的某些registration.aspx一样。

但是,当我启动其中一个页面时,我收到此错误:

Object reference not set to an instance of an object.

这是我的代码:

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();
}

1 个答案:

答案 0 :(得分:2)

实例化新的Helper(即新的System.Web.UI.Page)在整页请求中不存在,因此它没有对同一Master的引用(如果它甚至有一个)。相反,重新设计Helper以获取Master(或Page):

public class Helper
{
    private Page AssociatedPage;

    public Helper(Page page)
    {
        this.AssociatedPage = page;
    }

    public void hideLinks(){
        // error is produced at the following line at the start of
        // login.aspx or registration.aspx pages.
        LinkButton profile = (LinkButton)AssociatedPage.Master.FindControl("LinkButton1");
        LinkButton logout = (LinkButton)AssociatedPage.Master.FindControl("LinkButton2");

        profile.Visible = false;
        logout.Visible = false;
    }        
}

然后您的用法可能如下:

void Page_PreInit(object sender, EventArgs e)
{
   Helper master_helper = new Helper(this);
   master_helper.hideLinks();
}

您还可以将方法重新设计为静态,只需使用Page方法作为参数传递Master(或hideLinks)引用,但这取决于您