开发者

WinForm Applications event handler

I am just trying my hand at some WinForm Applications and was creating a simple event handle开发者_StackOverflowr, but I get an error message. Code:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public delegate void MyHandler1(object sender, EventArgs e);

        public Form1()
        {
            InitializeComponent();

            List<string> names = new List<string>();
            names.Add("S");
            names.Add("I");
            names.Add("G");

            MyHandler1 onClicked = new MyHandler1(clicked);

            listBox1.DataSource = names;
            listBox1.Click += onClicked;


        }

        public void clicked(object sender, EventArgs e)
        {
            label1.ResetText();
            label1.Text = listBox1.SelectedItem.ToString();
        }
    }

}

Error:

Error   1   Cannot implicitly convert type 'WindowsFormsApplication1.Form1.MyHandler1' to 'System.EventHandler'


The reason that your code doesn't compile is that implicit conversions do not exist between different delegate-types, even when the signatures are 'compatible'.

Try either of these:

// Implicit method-group conversion, should work from C# 2.0 or later.
// Essentially shorthand for listBox1.Click += new EventHandler(clicked);
listBox1.Click += clicked; 

// Creating a delegate-instance from a 'compatible' delegate,
// a trick I recently learnt from his highness Jon Skeet
listBox1.Click += new EventHandler(onClicked);

As an aside, unless the intention is to learn how to use delegates, I suggest you don't create your own delegate-type when one that comes with the framework will do the job.


Just use this code instead:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public delegate void MyHandler1(object sender, EventArgs e);

        public Form1()
        {
            InitializeComponent();

            List<string> names = new List<string>();
            names.Add("S");
            names.Add("I");
            names.Add("G");

            listBox1.DataSource = names;
            listBox1.Click += clicked;


        }

        public void clicked(object sender, EventArgs e)
        {
            label1.ResetText();
            label1.Text = listBox1.SelectedItem.ToString();
        }
    }
}

You don't really need the EventHandler1 in order to listen to handle an event with clicked method.


You do not need to create an entirely new delegate type to subscribe to an existing event. The event you are subscribing to already uses the existing System.EventHandler delegate type.

You only need to do:

listBox1.Click += new EventHandler(onClicked);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜