Skip to content

Windows Forms GUI Chunks

Windows Forms (.NET Framework)


Use these short chunks as copy-and-adapt templates for common UI actions. All examples use different sample content so they are assessment-safe.

What is covered

  • Items.Add and Items.AddRange
  • SelectedIndex defaults and resets
  • SelectedItem checks
  • MessageBox.Show with titles, buttons, icons, and confirmation logic

1. Fill a ComboBox using Items.Add

Click to view code
private void Form1_Load(object sender, EventArgs e)
{
    comboBoxWorkshopType.Items.Clear();
    comboBoxWorkshopType.Items.Add("Beginner");
    comboBoxWorkshopType.Items.Add("Intermediate");
    comboBoxWorkshopType.Items.Add("Advanced");

    comboBoxWorkshopType.SelectedIndex = 0;
}

2. Fill a ComboBox using Items.AddRange

Click to view code
private void LoadSessionOptions()
{
    string[] sessionTimes = { "9:00 AM", "11:30 AM", "2:00 PM" };

    comboBoxSessionTime.Items.Clear();
    comboBoxSessionTime.Items.AddRange(sessionTimes);
    comboBoxSessionTime.SelectedIndex = 0;
}

3. Add one formatted line to a ListBox with Items.Add

Click to view code
string studentName = textBoxStudentName.Text.Trim();
string workshopType = comboBoxWorkshopType.SelectedItem.ToString();
int seats = (int)numericUpDownSeats.Value;

string displayLine = $"{studentName} - {workshopType} - {seats} seat(s)";
listBoxBookings.Items.Add(displayLine);

4. Reset UI controls after Save using SelectedIndex

Click to view code
textBoxStudentName.Clear();
comboBoxWorkshopType.SelectedIndex = 0;
comboBoxSessionTime.SelectedIndex = 0;
numericUpDownSeats.Value = 1;

5. Check SelectedItem before using it

Click to view code
if (comboBoxWorkshopType.SelectedItem == null)
{
    MessageBox.Show(
        "Please choose a workshop type.",
        "Input Error",
        MessageBoxButtons.OK,
        MessageBoxIcon.Warning
    );
    return;
}

string workshopType = comboBoxWorkshopType.SelectedItem.ToString();

6. Warning message with MessageBoxButtons.OK and MessageBoxIcon.Warning

Click to view code
if (string.IsNullOrWhiteSpace(textBoxStudentName.Text))
{
    MessageBox.Show(
        "Student name cannot be blank.",
        "Validation Error",
        MessageBoxButtons.OK,
        MessageBoxIcon.Warning
    );
    return;
}

7. Success message with MessageBoxIcon.Information

Click to view code
MessageBox.Show(
    "Booking saved successfully.",
    "Success",
    MessageBoxButtons.OK,
    MessageBoxIcon.Information
);

8. Yes/No confirmation with DialogResult

Click to view code
DialogResult result = MessageBox.Show(
    "Clear all booking entries?",
    "Confirm Clear",
    MessageBoxButtons.YesNo,
    MessageBoxIcon.Question
);

if (result == DialogResult.Yes)
{
    listBoxBookings.Items.Clear();
}