您的位置:首页 > 其它

自定义事件报未将对象引用设置到对象的实例异常处理办法

2008-10-10 09:59 429 查看
这两天做项目,想在一个用户控件里添加一个事件.该控件主要是里面封装了一个日期控件,当月分选择改变时产生事件,以通知调用页面进行相关数据的加载.参考了一下别的网上资料关于事件的还挺多,在MSDN里有如下一段

public class Publisher
{
// Declare the delegate (if using non-generic pattern).
public delegate void SampleEventHandler(object sender, SampleEventArgs e);

// Declare the event.
public event SampleEventHandler SampleEvent;

// Wrap the event in a protected virtual method
// to enable derived classes to raise the event.
protected virtual void RaiseSampleEvent()
{
// Raise the event by using the () operator.
SampleEvent(this, new SampleEventArgs("Hello"));
}
}

于是参照该例我写为:

public partial class DataControl : System.Web.UI.UserControl

{

public delegate void MonthChange(DateTime newDateTime);

public event MonthChange OnMonthChange;

protected void Page_Load(object sender, EventArgs e)

{

}

protected void calMonth_VisibleMonthChanged(object sender, MonthChangedEventArgs e)

{

DateTime dtime = e.NewDate;

OnMonthChange(dtime);

}

}

在aspx页面调用为

protected void Page_Load(object sender, EventArgs e)

{

PageRightMode = RightMode.Member;

DataControl1.OnMonthChange += new WebSite.UserControls.Common.DataControl.MonthChange(DataControl1_OnMonthChange);

}

//日期控件发生更改

void DataControl1_OnMonthChange(DateTime newDateTime)

{

DateTime dateStart = newDateTime.AddDays(1 - newDateTime.Day) ;

DateTime dateEnd = dateStart.AddMonths(1).AddDays(-1);

TransDetail1.StartDate = dateStart;

TransDetail1.EndDate = dateEnd;

TransDetail1.LoadData();

}

运行时执行正常,但当我把控件放到另一个页面时总出现如下错误:

将对象引用设置到对象的实例。 说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。

异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。

源错误:

行 26:             DateTime dtime = e.NewDate;
行 27:
行 28:            OnMonthChange(dtime);
行 29:
行 30:         }
源文件: e:/我的文档/开发/WebSystem/CW/App_Controls/Common/DataControl.ascx.cs 行: 28

百思不得其解,网上也没有找到相关资料,后来试了好多种方法发现可如下解决:

public partial class DataControl2 : System.Web.UI.UserControl

{

public delegate void MonthChange(DateTime newDateTime);

public event MonthChange OnMonthChange;

protected void Page_Load(object sender, EventArgs e)

{

}

protected void calMonth_VisibleMonthChanged(object sender, MonthChangedEventArgs e)

{

DateTime dtime = e.NewDate;

if (OnMonthChange != null)

{

OnMonthChange(dtime);

}

}

}

即加上那句判断是否为空的语句就正常了.总结一下,应该是这样,在控件里产生事件时必须进行判断事件是否存在.因为如果在外部有调用的话没问题,当外部没有调用该事件时就会发生"未将对象引用设置到实例"的异常.而我一开始一个页面正常一个页面报告错的原因就在此.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐