Events – C# Tutorial

Modern applications don’t run from start-to-finish, in a linear fashion. Instead, they must respond to user input, system events, and network requests. For example, a document-based application must update the document when the user types a letter. Similarly, a Web service must wait for an incoming Web request, process the request, and return the response.

The .NET Framework uses events to handle each of these scenarios. For example, if a user clicks a button, the .NET runtime raises the Button.Click event. To run code when a user clicks a button, create a method, and assign it to handle the Button.Click event.

When creating custom classes, you might need to define events that other applications can handle. For example, if you create a multi-threaded process that can run in the background, you would need to create an event that is called when the processing completes.

At the end of this lesson, you will be able to:

  • Respond to events
  • Raise events

Generating Events in Visual Studio

In this video, I describe how events work in the .NET Framework (transcript below):

Anything can initiate an event; it’s really up to the class. One of the most common events that you’ll work with is the Button.Click event.

The Button.Click event is initiated when the user clicks a Button. When that happens, the Button class raises the Click event. In turn, the .NET Framework Common Language Runtime (CLR) calls any methods that have added themselves as event handlers.

In Visual Basic, that is done with the AddHandler keyword. In C#, that is done with the += operator.

Automatically Generating Event Handlers with Visual Studio

This video shows you how to use Visual Studio to automatically generate event handlers (with the transcript below):

Most of the time, when you’re responding to an event, you’ll be responding to events initiated by graphical controls. The Visual Studio user interface makes it easy to generate methods that respond to events for controls. Simply click the control, select Events in the Properties pane, and then double-click the event you want to respond to. You’ll see that Visual Studio automatically generates the method header for you. All you need to do is write the code.

Visual Studio works exactly the same when developing in Visual Basic.

Now, I’ll demonstrate how the application runs. Click the button, and it runs the method that I typed, which was simply to display a message box that showed, “Hello, world”.

How to Manually Create Event Handlers

If you need to manually create an event handler, follow these steps:

1. Examine the delegate for the event to determine the parameters that the event handler must accept. For .NET Framework classes, you can look up the event in MSDN. Typically, event handlers must return void and accept two parameters: an Object and an EventArgs (or a derived class). The following code sample demonstrates a delegate:

public delegate void AlarmEventHandler(object sender, EventArgs e);

2. Create the method that will handle the event.

3. Add the event handler to link the event and the method you created.

private void button1_Click(object sender, EventArgs e) 

{

     // Method code  

}

this.button1.Click += new System.EventHandler(this.button1_Click);

How to Raise Events

In this video, I demonstrate how to raise events in C# and Visual Studio. The transcript follows:

You can create classes that methods that create an instance of your class can respond to.

The most common reason to do this is that your class is a control that the user interacts with. For example, the Button control calls the Click event when the user clicks it. There are other events, such as MouseOver, that is called when the user moves the mouse over the control.

The second common reason that you want to raise an event is because a class is asynchronous. In an asynchronous class, the calling method will call one of your classes member methods that performs a long-running calculation. Your class then does the work in the background, returning control to the original method. Your class, when the calculation is complete, can then raise the event and allowing the method that created an instance of your class to respond to it.

I’ll show you how to quickly create a simple class that raises an event.

I’m going to create a class called MyCalc that performs a calculation when the calling method calls a member method. Instead of returning it the conventional way, it’s going to return it by raising an event.

The first thing we need to do is to create a delegate for the event. You do that in C# using the delegate keyword. I’m going to call this KnowAnswer. I’m going to provide two parameters: the standard Object, which represents the method that sent it, and an instance of AnswerEventArgs.

I haven’t yet created AnswerEventArgs, but I’m going to do that now by deriving it from the EventArgs standard class built into the .NET Framework. IT automatically inherits all of the EventArgs members, and I’m going to add one more member called answer which is just an integer, in which the resulting class can place an integer.

Now I’m going to create a class called MyCalc. I’ll create an event using the event keyword. That’s the name of the delegate, and now I’ll actually create the event by naming it OnKnowAnswer.

I’m going to create a method called Add that adds two integers. I’m going to use those two integers to populate the answer member of AnswerEventArgs. First I’m going to create an instance of AnswerEventArgs.

Now that we’ve created that instance and populated the answer, I can actually call the event. Now, by providing the first parameter as this, I’m providing an instance of the class itself. The event handler could use that in some way; I won’t use it in this example, but sometimes it is useful. The second parameter, of course, is the instance of AnswerEventArgs which actually contains the result of the addition.

Now I just need to create an instance of my MyCalc class and call the Add method to raise the event, which will be handled by my event handler.

First I’ll create an instance of the class. Next, I’ll let VIsual Studio automatically generate the event handler–you’ll see it automatically generates it there.

Next I’m going to use the += operator to add the event handler. Notice that I haven’t created the event handler yet; Visual Studio can do this automatically. I’m going ot press the Tab key twice, and it automatically generates a method called mc_OnKnowAnswer.

Notice that it automatically generates code that throws an exception. I’m just going to remove that and add in a line that simply displays the answer to the console. Notice that I can access the answer member of my custom AnswerEventArgs class.

Now I just need to call the Add method and have it add any two integers. I’ll add a call to Console.ReadKey to pause the console.

Run the application, and as you can see, it successfully displays the answer.

Return to the .NET Framework Fundamentals Table of Contents.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>