Event Handlers in C# WinForms

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:

ControlEventWhat it means
ButtonClickUser clicks the button
TextBoxTextChangedText content has changed
FormLoadThe form has finished loading
ComboBoxSelectedIndexChangedNew 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
}
PartWhat it means
senderThe control that triggered the event
EventArgsExtra 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

ConceptDescription
Event HandlerA method that runs when an event occurs
senderThe object that triggered the event
EventArgsExtra data passed with the event
+=Used to connect an event to a handler
asType-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 MouseEventArgs for mouse clicks & positions
  • βœ… Handle form-level events like FormClosing
  • βœ… Raise your own custom events
  • βœ… Use KeyPress and KeyDown for keyboard input

πŸ’¬ Still unsure how sender or EventArgs works in your project?
We can help you wire up events or debug handlers anytime!