I am just trying my hand at some WinForm Applications and was creating a simple event handler, 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:
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.