How to Handle Events
Event handlers make up a large portion of Windows Form Coding.
There have been a lot of questions on the C# forum of late that stemmed from people creating Event Handlers incorrectly.
First lets look at how an event and its event handler works:
Each event is a piece of application-level information. The .net framework interprets lower level input and creates the events event. These events are processed by the frameworks event dispatcher which is responsible for the relationship between event and handler.
In order for the event dispatcher to call the correct event handler the event handler must be bound to the event.
This can be done several ways:
1) Using the Visual Studio Designer (see events.jpg)
Click on the control who's event you wish to handle.
Click on the lightning bolt at the top of the properties window to view available events.
Double click the empty box next to the event to create an empty event handler in your Form code and add the event handlers binding to the Form.designer.cs file.
2) Manually Bind event handler (see code snippet below)
In your code, after the control has been created (usually InitializeComponent() in the FormLoad), you can manually bind an event handler to an event using
button1.Click+=new EventHandler(button1_Click); This will inform the event dispatcher that when the Click event is raised on button1, the method button1_Click() should be called.
If you create your event handlers manually you must ensure that the method has the correct parameters to match the event handlers signature; for a buttons click event the parameters look like
private void button1_Click(object sender, EventArgs e) .
Edited by Geekitygeek: n/a