Mark As Completed Discussion

Event Handling in C

Event handling is an essential aspect of developing interactive Windows Forms applications in C#. It allows you to respond to user actions, such as clicking a button or pressing a key, by executing specific code.

To handle events in C#, you can use event handlers. An event handler is a method that gets executed when a specific event occurs. In Windows Forms applications, you can attach event handlers to controls, such as buttons, checkboxes, or textboxes.

Let's take a look at an example:

TEXT/X-CSHARP
1using System;
2using System.Windows.Forms;
3
4public class EventHandlingForm : Form
5{
6    public EventHandlingForm()
7    {
8        Button button = new Button
9        {
10            Text = "Click Me",
11            Location = new System.Drawing.Point(100, 100)
12        };
13        button.Click += (sender, e) =>
14        {
15            MessageBox.Show("Button Clicked!");
16        };
17        Controls.Add(button);
18    }
19
20    public static void Main()
21    {
22        Application.Run(new EventHandlingForm());
23    }
24}

In this example, we create a class EventHandlingForm that inherits from the Form class provided by Windows Forms. Inside the constructor of EventHandlingForm, we create a Button control with the text "Click Me" and a location on the form.

We then attach an event handler to the button.Click event using an anonymous function. When the button is clicked, the event handler displays a message box with the text "Button Clicked!".

Finally, we add the button to the form using the Controls.Add method, and we start the application by calling Application.Run(new EventHandlingForm()).

Event handling is a powerful concept that enables you to create dynamic and interactive user interfaces in your Windows Forms applications. By attaching event handlers to controls, you can define custom behavior for your application's user interface based on user actions.

Try running the example code and clicking the button to see the event handling in action! Feel free to explore different events and attach event handlers to other controls to enhance the interactivity of your Windows Forms applications.

C#
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment