Working with events in C#

Events are a basic concept in programming. In our continuing series on C# fundamentals, we'll walk you through the process of creating events using Visual Studio .NET.

An event is a class member that activates when triggered by a button click or similar action. Events can fire off almost any response on any object you designate. Event methods track input, such as button-clicks, and can report such action across methods.

In this part of our introductory series on C#, I'll cover the basic elements of working with events in the context of a Windows form and how to use Visual Studio to add procedures to handle a form event, also known as an event handler. I’ll also examine the code behind an event method, so that you can add an event strictly in the code editor without using the visual development environment.

More C# for newbies
This article is part of a series we're calling "C# for Newbies" that's intended to ease the learning curve and help newcomers get started with C#. The first article of this series explained the basics of working with form classes. In our second article, we show you how to open specific instances of forms—a crucial skill in building multiform Windows applications.

What is an event?
An event is a placeholder for code that is executed when the event is triggered, or fired. Events are fired by a user action, program code, or by the system.

From a more formal perspective—and the C# point of view—an event is an object member, specifically a method. (This article focuses primarily on Windows forms, but the principals we'll discuss apply equally to objects such as buttons and other controls.

The event method, or event procedure, formally consists of the procedure name followed by two arguments. The first argument, or parameter, is the object firing the event; the second argument is of the type System.EventArgs. In addition, you must use the += operator to hook up the event method as a delegate, which is a method that stands in for another method. You may be familiar with += in its role as the C# additive assignment operator.

To make this more concrete, let's look at how a form click event for a form class named Form1 would be wired. (You’ll find this code in the InitializeComponent method in the “hidden” region of Windows Form Designer generated code):
this.Click += new System.EventHandler(this.Form1_Click);

The related framework for the event method is:
private void Form1_Click(object sender, System.EventArgs e) {

It's easy to invoke one event from another event. For example, the following code displays a message box when the Enter event of button1 is fired:
private void button1_Enter(object sender, System.EventArgs e) {
   MessageBox.Show ("The Button's Enter event has been fired",
      "C# for Newbies", MessageBoxButtons.OK, 

To invoke the button1 Enter event from another event, add a call to the button1_Enter method in the other event. In a form’s DoubleClick event, the code would be:
private void Form1_DoubleClick(object sender, System.EventArgs e) {
   button1_Enter (sender, e);

Now when the form is double-clicked, the message box displayed by firing the button’s Enter event will appear, as shown in Figure A.

Figure A
Events are handy for launching notifications such as this one.

You may not have a System.EventArgs to pass the event; for example, you might be invoking it outside an event. But that's not a problem, since you can create one and invoke an event method as follows:
System.EventArgs g = new System.EventArgs();
button1_Enter (this, g);

Using the Events tab
The Visual Studio IDE for VB.NET offers the Code Editor's Objects and Procedures drop-down lists to autogenerate event scaffolding. This works differently in C#, which uses a special interface to autogenerate event code scaffolding. To access this interface, first make sure the form is active in its designer (of course, this interface works for other objects, such as buttons, that are seated on the form). Next, open the Properties window and access the Events tab by clicking the lightening bolt icon on the Properties window toolbar.

You can use the Events tab of the Properties window in three ways:
  • Double-clicking in the left-hand column, which displays available events, creates an event-method scaffolding.
  • Selecting a method from the drop-down list in the right-hand column assigns the event to an existing class method, as shown in Figure B.
  •  Typing a new method name in the right-hand column assigns an event to a newly created method.

Figure B
Use the right-hand column's drop-down list to assign an event to an existing class method.

Let’s take a closer look at the first approach. If you double-click on the Click event in the left-hand column, the following code will be generated:
this.Click += new System.EventHandler(this.Form1_Click);
private void Form1_Click(object sender, System.EventArgs e) {


You can easily add code that displays a message box to the event method, as follows:
private void Form1_Click(object sender, System.EventArgs e) {
   MessageBox.Show ("I've been clicked!",
      "C# for Newbies", MessageBoxButtons.OK,

As you’d expect, when the form is clicked, the message box in Figure C is displayed.

Figure C
Our sample event presents this message.

As I noted earlier, you don’t have to use the default name for the event method (such as Form1_Click). This name is generated as a convenience; you can choose a different event-handler from the drop-down list.

It's important to note that one event method can handle multiple events, and the events don’t have to be fired by the same object. This is a great way to centralize processing of a particular set of events, such as all click events for a number of different controls. You can use the sender parameter within the event method to find out which object fired the event, and process the event accordingly. (Using the sender parameter in this fashion may involve type casting, which I’ll explain in detail in later articles.)

You can also use the Events pane to name the method that responds to a given event; just type your desired name in the right-hand column, as shown in Figure D.

Figure D
You can overwrite events' default names.

If you name the form’s SizeChanged event ICanNameThisWhatIWant, the following scaffolding is generated for the SizeChanged event:
this.SizeChanged += new System.EventHandler(this.ICanNameThisWhatIWant);
private void ICanNameThisWhatIWant(object sender, System.EventArgs e) {

Once again, it’s easy to add code that displays a message box (or performs some other task) to the event method:
private void ICanNameThisWhatIWant(object sender, System.EventArgs e) {
   MessageBox.Show ("Named my way!",
      "C# for Newbies", MessageBoxButtons.OK,

With this code in place, if the event is triggered by a form SizeChanged event, the code in the ICanNameThisWhatIWant method is processed and the desired message box is displayed.

Get to know the guts of events
Throughout this article I’ve emphasized the code generated by the development environment. Why? Because you should understand the underlying code for events. The visual development environment just doesn’t buy you that much in this area, and you'll often find it easier just to work in code, ignoring the Events tab. Why bother with the autogeneration mechanism once you get the hang of the code basics?

All this is quite helpful if you can get by with the canned events that ship with objects such as forms and buttons. But what if you want to create classes with their own events? How are custom events fired? Where do you put the code that these events should process? To find the answer to these questions, tune into the second part of this series.

Editor's Picks