Event Handling ⚡
Making Your App Respond to User Actions
Beginner Friendly
20 min read
Lesson 3 of 7
Let's Make Your App Interactive! 🎯
In this lesson, you'll learn about events - the magic that makes your app respond when users click, type, or do anything!
By the end of this lesson, you'll be able to:
- ✅ Understand what events are and why they matter
- ✅ Handle button clicks (the most common event)
- ✅ Use Form Load to setup your app
- ✅ Validate user input in real-time
- ✅ Handle form closing (confirm unsaved changes)
- ✅ Understand the event-driven programming model
- ✅ Feel confident making your apps interactive!
What Are Events?
In Simple Words: Events are like "notifications"
that your app sends when something happens. You write code that "listens"
for these notifications and responds to them!
🔔 Real-World Analogy
Think of events like a doorbell:
- 🚪 The Doorbell = The event (something happened)
- 👂 You Listening = The event handler (waiting for it)
- 🚶 Opening the Door = The response (what you do)
In WinForms:
- 🖱️ Button Click = "Someone pressed the button!"
- ⌨️ Text Changed = "Someone typed something!"
- 🪟 Form Load = "The form just opened!"
💻 Code Time!
Basic Event Handler:
private void btnClickMe_Click(object sender, EventArgs e)
{
// This code runs when the button is clicked!
MessageBox.Show("You clicked me!");
}
Explanation:
- sender - Which control triggered the event
- EventArgs - Additional information about the event
- Inside { } - Your code that runs!
😂 Fun Fact: Events are so common that
most developers don't even think about them - they just know
"double-click the button and write code"!
How Events Work
📝 The Event Pattern
Three things happen with every event:
- Event happens - User clicks, types, etc.
- Event fires - The control says "Hey, someone did something!"
- Handler runs - Your code executes in response
// 1. Event is defined in the control
public event EventHandler Click;
// 2. Event is raised (fired)
if (Click != null)
Click(this, EventArgs.Empty);
// 3. Your handler responds
private void btn_Click(object sender, EventArgs e)
{
// Your code here
}
🔗 Wiring Up Events
Two ways to connect events:
- Designer (Easy) - Double-click the control
- Code (Manual) - Write the connection yourself
// Manual wiring (in Form1.cs)
public Form1()
{
InitializeComponent();
btnSave.Click += new EventHandler(btnSave_Click);
}
// Or even shorter (modern C#)
public Form1()
{
InitializeComponent();
btnSave.Click += btnSave_Click;
}
✨ Visual Studio does this for you automatically when you double-click!
Pro Tip: You can wire multiple events to the same handler!
btnSave.Click += btnSave_Click; btnCancel.Click += btnSave_Click;
The Most Common Events
| Event | When It Happens | Common Control | Example Use |
|---|---|---|---|
| Click | User clicks the control | Button, Label | Save, Submit, Cancel |
| Load | Form first appears | Form | Load data, setup controls |
| TextChanged | Text in TextBox changes | TextBox | Real-time validation |
| SelectedIndexChanged | User changes selection | ComboBox, ListBox | Update other controls |
| FormClosing | Form is about to close | Form | Confirm unsaved changes |
| MouseHover | Mouse hovers over control | Any control | Show tooltip, highlight |
| KeyPress | User presses a key | TextBox | Filter input (numbers only) |
😂 Fun Fact: The most common event in WinForms is Click -
it's the "Hello World" of events! You'll use it more than any other.
Form Load - Setting Up Your App
What is Form Load? The
Load event fires once
when the form first appears. It's the perfect place to setup your app!
📝 Basic Form Load
private void Form1_Load(object sender, EventArgs e)
{
// Populate a ComboBox
cmbDepartment.Items.AddRange(new string[]
{ "IT", "HR", "Finance" });
cmbDepartment.SelectedIndex = 0;
// Set default values
txtDate.Text = DateTime.Now.ToShortDateString();
lblStatus.Text = "Ready";
// Disable button until ready
btnSave.Enabled = false;
}
✅ Common Setup Tasks
- 📋 Load data from database
- 📊 Populate dropdowns with options
- 📅 Set default values (today's date, etc.)
- 🎨 Configure UI (enable/disable controls)
- 🔍 Set focus to the first field
Pro Tip: Always use Form Load instead of the constructor
for UI setup. The form is fully ready by then!
😂 Joke: Why did the form load?
Because it had a lot to process! (Bad pun, I know 😅)
TextChanged - Real-time Validation
What is TextChanged? This event fires every time
the user types or changes text in a TextBox. It's great for real-time validation!
📝 Example: Email Validation
private void txtEmail_TextChanged(object sender, EventArgs e)
{
// Check if email contains '@'
bool isValid = txtEmail.Text.Contains("@");
// Update UI based on validation
btnSave.Enabled = isValid;
lblEmailStatus.Text = isValid ? "✅ Valid email" : "❌ Invalid email";
lblEmailStatus.ForeColor = isValid ? Color.Green : Color.Red;
}
✅ Common Uses
- ✉️ Email validation - Check for @ symbol
- 📱 Phone number - Format as you type
- 🔑 Password strength - Show strength indicator
- 📊 Search - Filter results as user types
- 📝 Character count - Show remaining characters
Warning: TextChanged fires on EVERY key press -
keep your code fast and simple!
SelectedIndexChanged - Reacting to Choices
What is SelectedIndexChanged? This event fires when the user
selects something from a ComboBox or ListBox. Perfect for updating
other controls based on the selection!
📝 Example: Product Selection
private void cmbProducts_SelectedIndexChanged(object sender, EventArgs e)
{
// Get selected product
string product = cmbProducts.SelectedItem?.ToString();
if (product == null) return;
// Update other controls based on selection
switch (product)
{
case "Laptop":
txtPrice.Text = "999.99";
txtDescription.Text = "High-performance laptop";
break;
case "Mouse":
txtPrice.Text = "29.99";
txtDescription.Text = "Wireless mouse";
break;
default:
txtPrice.Text = "0.00";
txtDescription.Text = "Unknown product";
break;
}
}
✅ Common Uses
- 🛒 Product selection - Show price/description
- 🏙️ Country/City - Update city dropdown when country changes
- 📊 Filter data - Show different data based on selection
- 👤 User profile - Load user details when selected
Pro Tip: Always check if
SelectedItem is null
before using it - it might be empty!
FormClosing - Confirming Exit
What is FormClosing? This event fires when the user tries to
close the form. It's your chance to ask "Are you sure?" or
save unsaved changes!
📝 Confirm Before Closing
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Ask user if they want to close
DialogResult result = MessageBox.Show(
"Are you sure you want to exit?",
"Confirm Exit",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question
);
// Cancel closing if user clicks No
if (result == DialogResult.No)
{
e.Cancel = true; // ⛔ Stop the form from closing
}
}
✅ Common Uses
- 💾 Save unsaved changes - "Save before closing?"
- 🔒 Confirm exit - "Are you sure?"
- 📋 Clean up - Close database connections
- 📊 Save state - Remember window position
Important: If you set
e.Cancel = true,
the form won't close!
😂 Joke: Why did the form refuse to close?
Because it had too many open tabs! (Get it? Tabs? ...I'll stop 😅)
Let's Practice! 🎮
Your Challenge: Create a login form with multiple event handlers!
Your Mission:
- Create a new WinForms project
- Name it "LoginForm"
- Add these controls:
- 📝 Labels for "Username" and "Password"
- ✏️ TextBoxes for each (txtUsername, txtPassword)
- 🔘 A Button for "Login"
- 🏷️ A Label for status messages
- Add these event handlers:
- 🔄 Form Load - Set focus to username
- ✏️ TextChanged - Enable Login button when both fields filled
- 🔘 Click - Validate and show success/error
- 🚪 FormClosing - Confirm exit
💡 What You'll Learn:
- ✅ How to handle multiple events
- ✅ How to validate user input
- ✅ How to enable/disable controls based on input
- ✅ How to confirm before closing
Result: A working login form with multiple event handlers!
// ===== LOGIN FORM =====
public partial class LoginForm : Form
{
// 🔒 Dummy credentials for validation
private const string VALID_USERNAME = "admin";
private const string VALID_PASSWORD = "1234";
public LoginForm()
{
InitializeComponent();
}
// 🔄 Form Load - Setup the form
private void LoginForm_Load(object sender, EventArgs e)
{
// Set focus to username field
txtUsername.Focus();
btnLogin.Enabled = false;
lblStatus.Text = "Enter your credentials";
lblStatus.ForeColor = Color.Blue;
}
// ✏️ TextChanged - Real-time validation
private void txtUsername_TextChanged(object sender, EventArgs e)
{
CheckLoginButton();
}
private void txtPassword_TextChanged(object sender, EventArgs e)
{
CheckLoginButton();
}
private void CheckLoginButton()
{
// Enable Login button only if both fields have text
bool hasUsername = !string.IsNullOrWhiteSpace(txtUsername.Text);
bool hasPassword = !string.IsNullOrWhiteSpace(txtPassword.Text);
btnLogin.Enabled = hasUsername && hasPassword;
if (btnLogin.Enabled)
{
lblStatus.Text = "Ready to login";
lblStatus.ForeColor = Color.Green;
}
else
{
lblStatus.Text = "Please fill in all fields";
lblStatus.ForeColor = Color.Red;
}
}
// 🔘 Login Button Click
private void btnLogin_Click(object sender, EventArgs e)
{
// Get user input
string username = txtUsername.Text;
string password = txtPassword.Text;
// 🔒 Validate credentials
if (username == VALID_USERNAME && password == VALID_PASSWORD)
{
// ✅ Success
lblStatus.Text = "✅ Login successful!";
lblStatus.ForeColor = Color.Green;
MessageBox.Show($"Welcome, {username}!", "Success");
// Optional: Open main form here
// MainForm main = new MainForm();
// main.Show();
// this.Hide();
}
else
{
// ❌ Error
lblStatus.Text = "❌ Invalid username or password!";
lblStatus.ForeColor = Color.Red;
MessageBox.Show("Invalid credentials. Please try again.",
"Login Failed", MessageBoxButtons.OK,
MessageBoxIcon.Error);
// Clear and refocus
txtPassword.Clear();
txtUsername.Focus();
}
}
// 🚪 Form Closing - Confirm exit
private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult result = MessageBox.Show(
"Are you sure you want to exit the application?",
"Confirm Exit",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question
);
if (result == DialogResult.No)
{
e.Cancel = true; // ⛔ Don't close
}
}
// 🔄 Optional: Reset button
private void btnReset_Click(object sender, EventArgs e)
{
txtUsername.Clear();
txtPassword.Clear();
txtUsername.Focus();
btnLogin.Enabled = false;
lblStatus.Text = "Fields cleared. Enter credentials.";
lblStatus.ForeColor = Color.Blue;
}
}
✅ Complete Solution!
You've built a login form with multiple event handlers!
🎉 What You Learned Today!
Events
NotificationsWiring
Connecting eventsLoad
Setup your appValidation
Real-time checkingSelectedIndexChanged
React to choicesFormClosing
Confirm exitLogin Example
Real-world appReady!
For any app!🎯 You're now ready to make any WinForms application interactive with events!