1

我是 ASP.net 的初学者,想创建一个类文件,其中包含我的应用程序中常用的方法。就像这里隐藏某些ButtonLink's 在login.aspxandregistration.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();
}
4

1 回答 1

2

实例化一个 new Helper(即一个 new System.Web.UI.Page)不作为整个页面请求的一部分存在,因此它没有对相同的引用Master(如果它甚至有一个)。相反,重新设计你HelperMaster(或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方法作为参数一起传入,但这取决于您。

于 2012-11-30T16:25:38.017 回答