C# Event Handler Example

EVENT-DRIVEN PROGRAMMING AND EVENT-HANDLING IN C#

by

Event handlers are an important concept for C# developers to master. In this tutorial, you will learn about event-driven programming by creating an example GUI application.

Event-Driven Programming

Throughout the beginners tutorial series, you learned to write code that runs sequentially. One line of code would execute, and then the next line, and the next line, and so forth. However, what if you want to write blocks of code that execute in response to a certain event, like when a user clicks a button in your application? This is called event-driven programming, and it will be the subject of this tutorial.

Appropriately handling events is essential when developing desktop, mobile, and web applications. Event-driven programming allows you to write code that responds to specific events that are raised in your application. Such events could be triggered by the application itself or by the user, such as when the user clicks a button or presses a key.

Handling Events

To get started, create a new C# Windows desktop application project. Specifically, we will be working with a Windows Presentation Foundation client application (File > New > Project...). Select WPF App. You might name your application EventHandlers. Your new project should open with a blank form.

From the Toolbox (on the left in the screenshot above), drag a Button and a Label onto the canvas. When you select an item, you will be able to modify its attributes, such as its Name, Content, and Visibility. The Name property is the control's unique identifier that you will reference in your C# code. The Content property is the text that will appear in the user interface. The Visibility property defines whether the control will be Hidden or Visible in the form. Feel free to play around with the code that is generated in the MainWindow.xaml file to get familiar with what each property does.

Assign a Name and update the Content properties of the UI elements to match the following XAML excerpt.

<Button x:Name="myButton" Content="Click me" HorizontalAlignment="Center" Margin="0,0,0,0" VerticalAlignment="Center" Width="75" Click="Button_Click"/>
<Label x:Name="statusLabel" HorizontalAlignment="Center" Margin="0,60,0,0" VerticalAlignment="Center"/>

Next, select myButton and click the lightning bolt icon. This will bring up a list of all the events that a Button can raise. In this exercise, we will focus on the Click event. This is the event that is triggered when a user clicks the button. In this example, we are interested in writing code that will execute when a user clicks the button. Specifically, we will change the content of a label in our application when a user clicks the button.

Double-click the white space next to the Click event in the Properties pane. This will automatically generate an event-handler method in MainWindow.xaml.cs called Button_Click().

This event handler is automatically attached to the Click event of the Button in the xaml code, as shown below.

<Button x:Name="myButton" Content="Click me" HorizontalAlignment="Center" Margin="0,0,0,0" VerticalAlignment="Center" Width="75" Click="Button_Click"/>

The code you write in the private void Button_Click(object sender, RoutedEventArgs e){ } method will be executed when the user clicks the button in your application.

Recall that you assigned the name statusLabel to the Label control in your user interface. You can programmatically modify the control's properties by referencing its Name and attribute. To change the Content of statusLabel, for example, your Button_Click method may look like the following:

private void Button_Click(object sender, RoutedEventArgs e)
{
    statusLabel.Content = "You clicked the button!";
}

Event Handling with Conditions

A Beginner's Approach

You can use the same technique (Name.Attribute = Value) to programmatically set the the initial values for a control's properties instead of setting them in the xaml file. To do this, modify the public MainWindow() method. Suppose you want to the label to appear when the user clicks the button, and then to disappear when the user clicks the button again. Set the initial values for statusLabel.

public MainWindow()
{
    InitializeComponent();
    statusLabel.Visibility = Visibility.Hidden;
    statusLabel.Content = "You clicked the button!";
}

In this approach, you will declare a private bool outside the MainWindow() method. Remember, you will be able to reference this private variable within the MainWindow class, but not outside the class. You can use it as a flag to keep up with the state of our application.

private bool isClicked = false;

Now, modify the Button_Click event Handler to change the Visibility of statusLabel based on the value of the boolean you just created.

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (!isClicked)
    {
        statusLabel.Visibility = Visibility.Visible;
        isClicked = true;
    }
    else
    {
        statusLabel.Visibility = Visibility.Hidden;
        isClicked = false;
    }
}

A Better Approach

The above approach works, but there is a better way to write the code. First, the boolean variable is unnecessary. The code can be written without it by directly checking the Visibility property itself. It is included in the tutorial as a proof-of-concept and a reminder about how variables work within their context.

Second, recall that the Ternary Conditional Operator can be used to replace this type of code logic. The entire contents of the Button_Click method can be replaced with a single line of code.

private void Button_Click(object sender, RoutedEventArgs e)
{
    statusLabel.Visibility = (statusLabel.Visibility == Visibility.Hidden) ? Visibility.Visible : Visibility.Hidden;
}

Multiple Event Handlers

Suppose you want to attach multiple event handlers to the same event? Previously you learned to assign an event handler to an event using either the visual editor or by modifying the .xaml code. However, you can also programmatically attach an event handler directly in your C# code. You can even attach multiple event handlers as demonstrated below:

public MainWindow()
{
    InitializeComponent();
    myButton.Click += Button_Click1;
    myButton.Click += Button_Click2;
}

You would then write two different event handler methods, corresponding to the names of the methods you attached. In this example, one would be named Button_Click1 and the other named Button_Click2.

private void 
private void Button_Click1(object sender, RoutedEventArgs e)
{
    //Do something else
}
Button_Click2(object sender, RoutedEventArgs e)
{
    //Do something
}

The Bottom Line

In this tutorial, you learned about event-driven programming. This is a crucial concept as you continue to write applications with non-trivial user interfaces. Whether you are writing ASP.NET, WPF, UWP, or Xamarin applications, you will need to know about event handlers. By working through examples, you learned several techniques for attaching event handlers to events. You also learned how to write event handler methods. If this C# tutorial helped you, let me know in the comments.


Don't stop learning!

There is so much to discover about C#. That's why I am making my favorite tips and tricks available for free. Enter your email address below to become a better .NET developer.


Did you know?

Our beautiful, multi-column C# reference guides contain more than 150 tips and examples to make it even easier to write better code.

Get your cheat sheets