C#自定义事件处理程序 [英] C# Custom Event Handler

查看:184
本文介绍了C#自定义事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习C#的人,和我有一个父窗体和子窗体的程序。我想子窗体引发一个事件,使母体形式可以做一些事情。我复制了一些代码,但我不够聪明,看看有什么是错的。我不知道如何正确的代码子窗体的事件。该错误是没有定义DatasourceUpdated。谁能帮我出一个修复建议?



在子窗体我有



 公共部分类窗体2:表
{
公共事件处理DataSourceUpdated;
...
私人无效button2_Click(对象发件人,EventArgs五)//完成按钮
{
如果(this.DataSourceUpdated!= NULL)//引发事件
{
this.DatasourceUpdated();
}

this.Close();
}

在我有这个父窗体:

 私人无效myAddRecord()
{
串身份识别码=的String.Empty;
串myMessage =插入;

窗体2 myForm会=新Form2的(身份识别码,myMessage);

Form2.DatasourceUpdated + = ChildUpdated;
myForm.Show();


解决方案

您的代码看起来正确的,据我可以告诉,只要你有一个实际的处理程序;您还没有在你的代码。 ChildUpdated 需要一个方法,它带有签名无效(对象发件人,EventArgs五),你也应该提高这样的事件 this.DataSourceUpdated(本,NULL);



的事实被指定的签名你声明事件由 System.EventHandler 被处理,其中有一个签名。你可以创建自己的代表以及,如果你希望它在所有接受了一些特殊参数或没有参数。



此外,你必须在你的例子不准确的外壳, this.DatasourceUpdated - > this.DataSourceUpdated ,但我认为这只是在你的榜样... <? / p>

I am a person learning c#, and I have a program with a Parent form and a Child form. I want the child form to raise an event so that the Parent form can do something. I copied some code, but I am not smart enough to see what is wrong. I don't know how to correctly code the event in the child form. The error is DatasourceUpdated is not defined. Can anyone help me out with a suggested fix?

In the Child form I have

public partial class Form2 : Form
{
   public EventHandler DataSourceUpdated;
   ...
   private void button2_Click(object sender, EventArgs e)  //Done button
   {
       if (this.DataSourceUpdated != null) //raise the event
       {
           this.DatasourceUpdated();
       }

       this.Close();
   }

In the parent form I have this:

private void myAddRecord()
{
    string myID = string.Empty;
    string myMessage = "Insert";

    Form2 myForm = new Form2(myID, myMessage);

    Form2.DatasourceUpdated += ChildUpdated;
    myForm.Show();

解决方案

Your code looks right, as far as I can tell, as long as you have an actual handler; you have not included that in your code. ChildUpdated needs to be a method that with the signature void (object sender, EventArgs e), and you should also raise the event like that this.DataSourceUpdated(this, null);

The signature is being specified by the fact that you're declaring the event as being handled by System.EventHandler, which has that signature. You can create your own delegates as well, if you want it to receive some special parameters or no parameters at all.

Also, you have an inaccurate casing in your example, this.DatasourceUpdated -> this.DataSourceUpdated, but I'll assume that's just in your example...?

这篇关于C#自定义事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆