22
Lesson 22 of 35 · WinForms

Controls & Event Handling

Controls are the building blocks of a WinForms UI. This lesson covers the most commonly used controls—Button, TextBox, Label, ListBox, ComboBox, CheckBox, RadioButton—and how to wire up events.

Button

The Button fires a Click event. Double-click it in the designer to auto-generate the handler. Key properties: Text, BackColor, ForeColor, Font, Enabled.

Button click ButtonClick.cs
private void btnSubmit_Click(object sender, EventArgs e)
{
    string name = txtName.Text.Trim();
    if (string.IsNullOrEmpty(name))
    {
        MessageBox.Show("Please enter your name.", "Validation",
            MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
    }
    lblGreeting.Text = $"Hello, {name}!";
}

TextBox

Key TextBox properties: Text, Multiline, PasswordChar, MaxLength, ReadOnly. The TextChanged event fires every time the text changes.

ListBox & ComboBox

Add items with Items.Add() or at design time. The SelectedItem property returns the selected object; SelectedIndex returns its position. ComboBox combines a text box with a drop-down list.

ListBox example ListBoxDemo.cs
// Populate at runtime
listBox1.Items.AddRange(new[] { "Apple", "Banana", "Cherry" });

// Handle selection
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    lblSelection.Text = $"Selected: {listBox1.SelectedItem}";
}

CheckBox & RadioButton

CheckBox.Checked returns a bool. Group RadioButtons inside a GroupBox or Panel—only one in the group can be checked at a time.

CheckBox usage CheckDemo.cs
private void btnApply_Click(object sender, EventArgs e)
{
    var sb = new System.Text.StringBuilder();
    if (chkBold.Checked)   sb.Append("Bold ");
    if (chkItalic.Checked) sb.Append("Italic ");
    if (chkUnder.Checked)  sb.Append("Underline");
    lblStyle.Text = sb.ToString();
}