Event-driven Programming and C# Event Handler Examples
Tags: csharp, tutorial, advanced
Published: 2019-09-03 09:32:37

---
title: Event-driven Programming and C# Event Handler Examples
published: true
tags: csharp,tutorial,advanced
canonical_url: https://wellsb.com/csharp/advanced/csharp-event-handler-example/
---
[Source](https://wellsb.com/csharp/advanced/csharp-event-handler-example/)
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](https://wellsb.com/csharp/tutorials/beginners/), 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.

[![](https://wellsb.com/csharp/wp-content/uploads/sites/2/2019/08/wpf-eventhandlers1-min-300x169.png)](https://wellsb.com/csharp/wp-content/uploads/sites/2/2019/08/wpf-eventhandlers1-min.png)

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.

```csharp
<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.

[![](https://wellsb.com/csharp/wp-content/uploads/sites/2/2019/08/wpf-eventhandlers2-min-300x185.png)](https://wellsb.com/csharp/wp-content/uploads/sites/2/2019/08/wpf-eventhandlers2-min.png)

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.

```csharp
<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:

```csharp
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.

```csharp
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.

```csharp
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.

```csharp
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](https://wellsb.com/csharp/beginners/csharp-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.

```csharp
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:

```csharp
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.

```csharp
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.

[Source](https://wellsb.com/csharp/advanced/csharp-event-handler-example/)