本文介绍了UserControl上的自定义事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果找到了一段代码,使您可以在用户控件上创建自己的事件.伟大的!但这对我不起作用.这是(已更改为我的情况)代码:
用户控件:
Hi,
If have found a piece of code that allows you to create own events on a usercontrol. Great! But it doesn''t work with me. This is the (changed to my situation) code:
Usercontrol:
public partial class Usercontrols_Modal : System.Web.UI.UserControl
{
public delegate void ResultCompletedEventHandler(object sender, ReturnResultArgs e);
public event ResultCompletedEventHandler ReturnResult;
protected void btnYes_Click(object sender, EventArgs e)
{
ReturnResultArgs args = new ReturnResultArgs();
args.Result = true;
this.ReturnResult(this, args);
}
}
public class ReturnResultArgs : EventArgs
{
// this is a string value I will set using a dropdownlist
public Boolean Result { get; set; }
}
在网络表单上(后面的代码):
On the webform (code behind):
public void AskQuestion(object sender, EventArgs e)
{
modaldelete.ReturnResult +=new Usercontrols_Modal.ResultCompletedEventHandler(modaldelete_ReturnResult);
//modaldelete.SearchCompleted +=new Usercontrols_Modal.SearchCompletedEventHandler(modaldelete_SearchCompleted);
modaldelete.Visible = true;
}
protected void modaldelete_ReturnResult(object sender, ReturnResultArgs e)
{
Response.Redirect("/default.aspx");
}
我的代码在this.ReturnResult(this,args);上中断.看来ReturnResult为null,无法继续.
我做错了什么?
在此先感谢
My code breaks on this.ReturnResult(this, args);. It seems ReturnResult is null and cannot continue.
What am I doing wrong??
Thanks in advance
推荐答案
if (this.ReturnResult != null) {
ReturnResultArgs args = new ReturnResultArgs();
args.Result = true;
this.ReturnResult(this, args);
}
如果在AskQuestion中订阅事件之前执行了btnYes_Click,那么您将得到所提到的错误.
If btnYes_Click is executed before the event is subscribed in AskQuestion, then you would get the error mentioned.
这篇关于UserControl上的自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!