C#自定义事件始终为null

时间:2015-05-13 07:17:42

标签: c# asp.net events webforms

我知道现在有一些关于stackOverFlow这个问题的问题,但是没有一个能解决我的问题。

我使用" asp.net webform"在我点击UserControl时我想要的Button中,在使用此UserControl的页面中触发事件。所以这是我的代码。

// in user control
public delegate void OnConversationSubmitDelegate(object sender, EventArgs e);
public event OnConversationSubmitDelegate OnConversationSubmitEvenet;

protected void btnUserSubmit_Click(object sender, EventArgs e)
{
    if (OnConversationSubmitEvenet != null) //This is always null
    {
        OnConversationSubmitEvenet(this, new EventArgs());
    }
}

// in main page
protected void Page_Load(object sender, EventArgs e)
{
    UserControls.ConversationBox m = new UserControls.ConversationBox();
    m.OnConversationSubmitEvenet += new UserControls.ConversationBox.OnConversationSubmitDelegate(Test_Event);
}

public static void Test_Event(object sender, EventArgs e)
{
    string g = "sdfsd";
}

问题是OnConversationSubmitEvenet始终为空,Test_Event方法永远不会运行。

2 个答案:

答案 0 :(得分:1)

似乎是你在Page_Load中创建了一个新的ConversationBox,但我怀疑你没有将它添加到页面控件中,你还在aspx中添加了一个ConversationBox?

如果您确实在aspx中添加了ConversationBox,那么请改为:

 UserControls.ConversationBox m = new UserControls.ConversationBox();
 m.OnConversationSubmitEvenet += new UserControls.ConversationBox.OnConversationSubmitDelegate(Test_Event);

您应该使用在aspx中添加的ConversationBox:

myConversationBox.OnConversationSubmitEvenet += new UserControls.ConversationBox.OnConversationSubmitDelegate(Test_Event);

或者你也可以删除aspx中添加的那个,而是将 m 添加到页面控件中:

UserControls.ConversationBox m = new UserControls.ConversationBox();
m.OnConversationSubmitEvenet += new UserControls.ConversationBox.OnConversationSubmitDelegate(Test_Event);
Page.Controls.Add(m); // This line adds the control to the page

答案 1 :(得分:-1)

你应该在表单中声明'm'作为字段,因为现在'm'是在'Load'方法执行后消失的局部变量。

相关问题