I’m new to c# so apologies if this is a noob question. I’m trying to get clarity around the syntax or pattern for handling events in c#.
So I have a Form object Form1 and a Button button1 in the form. I handle a Click event with a method like this in Form1.cs:
private void button1_Click(object sender, EventArgs e)
{
Debug.WriteLine("click!");
}
which works fine. Now in another form Form2 I have a TreeView treeView1, and I want to handle the BeforeExpand event. So I assumed it would be:
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
Debug.WriteLine("Hello!");
}
which in fact doesn’t work: this method is never called when I expand a node. But several SO answers imply this is the way to do it, e.g this one.
Anyway I found an alternative approach which does work for me. In the form constructor bind the event handler like this:
treeView1.BeforeExpand += new TreeViewCancelEventHandler(anyMethodNameYouLike);
So what’s the difference between these two approaches? Why doesn’t the _event syntax work for a treeview? Is there some difference between the event types?
Thanks
I assume you doubleclicked the button in the Visual Studio designer. The
button1_Clickhandler got added automatically, just like you created theBeforeExpandhandler by hand.Check your Form1.Designer.cs file, you’ll find a line something like this: