Understanding sender, event arguments, and how events work
Windows Forms apps are event-driven β they sit and wait for the user to do something (like click a button), then respond with code. This is where event handlers come in.
π§° What Is an Event Handler?
An event handler is a method that runs when something happens β like a button being clicked, the mouse moving, or a textbox losing focus.
myButton.Click += MyClickHandler;
Here, youβre telling the button to run MyClickHandler when itβs clicked.
π Getting Started
π Common Events in WinForms:
| Control | Event | What it means |
|---|---|---|
Button | Click | User clicks the button |
TextBox | TextChanged | Text content has changed |
Form | Load | The form has finished loading |
ComboBox | SelectedIndexChanged | New item selected |
π§© Event Handler Syntax
Every event has a standard method signature:
private void button1_Click(object sender, EventArgs e)
{
// This code runs when the button is clicked
}
| Part | What it means |
|---|---|
sender | The control that triggered the event |
EventArgs | Extra info about the event (can be subclassed) |
β You can assign it manually or use the Visual Studio designer to double-click the control and auto-generate it.
π§ͺ Example: Show Which Button Was Clicked
private void button_Click(object sender, EventArgs e)
{
Button clicked = sender as Button;
if (clicked != null)
{
MessageBox.Show("You clicked: " + clicked.Text);
}
}
Set it up:
button1.Click += button_Click;
button2.Click += button_Click;
π§ sender helps you reuse one event handler for multiple controls.
π Custom EventArgs
Sometimes built-in EventArgs isn’t enough. You can define your own:
public class ScoreEventArgs : EventArgs
{
public int Score { get; set; }
}
Useful when creating custom controls or raising your own events.
π§± Full Example: Text Change Logger
private void textBox1_TextChanged(object sender, EventArgs e)
{
TextBox changedBox = sender as TextBox;
Console.WriteLine("New text: " + changedBox.Text);
}
β
Works with multiple textboxes β use sender to identify which was changed.
π Summary
| Concept | Description |
|---|---|
Event Handler | A method that runs when an event occurs |
sender | The object that triggered the event |
EventArgs | Extra data passed with the event |
+= | Used to connect an event to a handler |
as | Type-casts the sender to a specific control |
π§ͺ Quick Challenge
π§© Create 3 buttons. When any button is clicked, display a message like:
You clicked: Button 1
π‘ Hint: Use a shared event handler and check ((Button)sender).Text.
π Want to Go Deeper?
- β
Use
MouseEventArgsfor mouse clicks & positions - β
Handle form-level events like
FormClosing - β Raise your own custom events
- β
Use
KeyPressandKeyDownfor keyboard input
π¬ Still unsure how sender or EventArgs works in your project?
We can help you wire up events or debug handlers anytime!