Lesson 4

Handling Events

An event is something that a control raises to tell the program that something significant has happened. Events are extremely important because they are the main way the user controls the program. When the user clicks buttons, drags sliders, and selects menu items, events tell the program that something has happened so it can take action.

An event handler is a piece of code that catches the event and executes when an event occurs. The event handler might display a message, perform a calculation, or download the latest Dilbert comic from the web.

Lesson 2 briefly explained how you can catch a Button's Click event, but that event is only one of hundreds (if not thousands) of events that your programs can catch.

This lesson explains how you can catch events other than Click. It describes some of the most useful events provided by common controls and, as a bonus, explains how you can display messages to the user when events occur.

Making Event Handlers

The easiest way to build an event handler is to double-click a control in the Form Designer. This creates an empty event handler for the control's default event and opens the event handler in the Code Editor. You can then type C# code to take whatever action is appropriate.

The following code shows the empty Click event handler created for a Button:

private void crashSystemButton_Click(object sender, EventArgs e)

Probably the most commonly used events are the Click events raised by Buttons, ToolStripMenuItem ...

Get C# 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.