.NET ProgrammingUnit 511 min read

Windows Forms Apps: Controls, Events & UI Design

Unit 5 of .NET Programming covers designing interactive Windows desktop applications using C and Visual Studio, including form layout, event handling, common controls (buttons, textboxes, lists), and data binding—essential for building user-friendly software.

Core Concepts

What is a Windows Forms Application?

A Windows Forms Application is a type of desktop application built using Microsoft’s .NET Framework that runs on Windows. It uses a graphical user interface (GUI) built with forms (windows), controls (UI elements), and events (user interactions). Unlike web apps, Windows Forms apps are installed locally and run offline.

Why use Windows Forms?

  • Simple to develop for Windows-only applications.
  • Rich set of built-in controls (buttons, menus, dialogs).
  • Tight integration with .NET libraries.

Key Components of Windows Forms

1. Forms (Windows)

A Form is the main container for your application’s UI. It can hold other controls like buttons, textboxes, and labels.

Example:

using System;
using System.Windows.Forms;

class MyForm : Form
{
    public MyForm()
    {
        this.Text = "My First Form";
        this.Size = new System.Drawing.Size(400, 300);
        Button btn = new Button();
        btn.Text = "Click Me!";
        btn.Location = new System.Drawing.Point(100, 100);
        this.Controls.Add(btn);
    }
}

Visualization: Form with a Button

classDiagram
    class Form {
        +Text: string
        +Size: Size
        +Controls: ControlCollection
    }
    class Button {
        +Text: string
        +Location: Point
    }
    Form "1" --> "*" Control : contains
    Form --> Button : example

2. Controls (UI Elements)

Controls are interactive elements like buttons, textboxes, checkboxes, etc. They are added to forms using the Toolbox in Visual Studio.

Common Controls:

Control Purpose Example Usage
Button Triggers actions when clicked. Submit, Cancel, OK buttons.
TextBox Single-line or multi-line text. Username, password fields.
Label Displays static text. Form titles, instructions.
CheckBox Toggle on/off options. Preferences (e.g., "Remember me").
RadioButton Single selection from options. Gender selection (Male/Female).
ListBox Displays a list of items. Dropdown menus (e.g., cities).
ComboBox Dropdown list with text input. Search-as-you-type filters.

Example: Adding a TextBox and Button

TextBox txtName = new TextBox();
txtName.Location = new Point(100, 50);
txtName.Size = new Size(200, 20);

Button btnSubmit = new Button();
btnSubmit.Text = "Submit";
btnSubmit.Location = new Point(100, 100);
btnSubmit.Click += (sender, e) => MessageBox.Show($"Hello, {txtName.Text}!");
this.Controls.Add(txtName);
this.Controls.Add(btnSubmit);

3. Events and Event Handling

Events are actions triggered by user interactions (e.g., clicking a button). You handle events using event handlers.

Common Events:

Event Triggered When
Click User clicks a button.
TextChanged Text in a TextBox is modified.
SelectedIndexChanged Item in a ListBox is selected.

Example: Handling a Button Click

btnSubmit.Click += (sender, e) =>
{
    string name = txtName.Text;
    MessageBox.Show($"Hello, {name}!");
};

Visualization: Event Flow

sequenceDiagram
    participant User
    participant Button
    participant Form
    User->>Button: Clicks
    Button->>Form: Raises Click Event
    Form->>EventHandler: Executes Code
    EventHandler->>User: Shows Message

Designing a Simple Application: Student Grade Calculator

Let’s build a form that calculates the average grade of a student.

Step 1: Create a Form

  1. Open Visual Studio → Create a Windows Forms App (.NET Framework).
  2. Design the form with:
    • 3 TextBox controls for subject grades.
    • 1 Button to calculate the average.
    • 1 Label to display the result.

Form Layout:

classDiagram
    class Form {
        +TextBox[] Grades
        +Button Calculate
        +Label Result
    }
    Form --> TextBox : 3 subjects
    Form --> Button : Calculate
    Form --> Label : Result

Step 2: Add Controls Programmatically

public partial class GradeCalculator : Form
{
    private TextBox[] txtGrades = new TextBox[3];
    private Button btnCalculate;
    private Label lblResult;

    public GradeCalculator()
    {
        InitializeComponent();
        SetupUI();
    }

    private void SetupUI()
    {
        // Add 3 TextBoxes for grades
        for (int i = 0; i < 3; i++)
        {
            txtGrades[i] = new TextBox();
            txtGrades[i].Location = new Point(50, 50 + (i * 30));
            txtGrades[i].Width = 100;
            this.Controls.Add(txtGrades[i]);
        }

        // Add Calculate Button
        btnCalculate = new Button();
        btnCalculate.Text = "Calculate Average";
        btnCalculate.Location = new Point(50, 150);
        btnCalculate.Click += CalculateAverage;
        this.Controls.Add(btnCalculate);

        // Add Result Label
        lblResult = new Label();
        lblResult.Location = new Point(200, 150);
        this.Controls.Add(lblResult);
    }

    private void CalculateAverage(object sender, EventArgs e)
    {
        double sum = 0;
        for (int i = 0; i < 3; i++)
        {
            if (double.TryParse(txtGrades[i].Text, out double grade))
            {
                sum += grade;
            }
        }
        double average = sum / 3;
        lblResult.Text = $"Average: {average:F2}";
    }
}

Step 3: Run the Application

  1. Press F5 to run.
  2. Enter grades in the textboxes and click Calculate Average.
  3. The result appears in the label.

Visualization: State After Input

classDiagram
    class Form {
        +TextBox[0] = "85"
        +TextBox[1] = "90"
        +TextBox[2] = "78"
        +Label = "Average: 84.33"
    }

In the Real World

  1. eSewa (Nepal)

    • Use of Windows Forms: Older versions of eSewa’s desktop client used Windows Forms for local bill payments and transaction history. The ListBox control displayed transaction records, and Button events triggered payments.
    • Example: When a user clicks the "Pay Bill" button, the Click event handler validates input (e.g., phone number, amount) and processes the payment via eSewa’s API.
  2. Banking Software (e.g., NMB Bank’s Loan Calculator)

    • Use of Windows Forms: Banks use Windows Forms apps for internal tools like loan calculators. A TextBox captures the loan amount, interest rate, and tenure, while a Button triggers the calculation. The result (monthly installment) is displayed in a Label.
    • Example: If a user enters:
      • Loan Amount: 5,00,000
      • Interest Rate: 8%
      • Tenure: 5 years The Calculate button’s event handler computes EMI using the formula: where , , .
  3. NTC’s Billing System (Older Versions)

    • Use of Windows Forms: NTC’s legacy billing software used Windows Forms for generating and printing bills. A ComboBox allowed users to select customer IDs, while a Button generated the bill and displayed it in a RichTextBox before printing.

Advanced Topics

1. Dialog Boxes

Dialog boxes (MessageBox, OpenFileDialog, SaveFileDialog) provide additional input/output options.

Example: File Selection Dialog

OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";

if (openFileDialog.ShowDialog() == DialogResult.OK)
{
    string filePath = openFileDialog.FileName;
    MessageBox.Show($"Selected File: {filePath}");
}

Visualization: Dialog Flow

flowchart TD
    A["User Clicks 'Open'"] --> B["OpenFileDialog Appears"]
    B -->|"User Selects File"| C["File Path Stored"]
    C --> D["MessageBox Shows Path"]

2. Data Binding

Bind controls to data sources (e.g., DataTable, List) to auto-update UI.

Example: Binding a ListBox to a List

List<string> subjects = new List<string> { "Math", "Science", "English" };
ListBox lstSubjects = new ListBox();
lstSubjects.DataSource = subjects;
this.Controls.Add(lstSubjects);

Visualization: Data Binding

classDiagram
    class List {
        +Items: string[]
    }
    class ListBox {
        +DataSource: List
    }
    List --> ListBox : Binds Automatically

3. Custom Controls

Create reusable controls by inheriting from existing ones.

Example: Custom Button with Animation

public class AnimatedButton : Button
{
    public AnimatedButton()
    {
        this.FlatStyle = FlatStyle.Flat;
        this.Click += (sender, e) =>
        {
            this.BackColor = Color.Red;
            System.Threading.Tasks.Task.Delay(500).ContinueWith(t =>
            {
                this.Invoke((MethodInvoker)delegate {
                    this.BackColor = SystemColors.Control;
                });
            });
        };
    }
}

Common Mistakes and How to Avoid Them

Mistake Solution
Forgetting to add controls to Controls collection. Always call this.Controls.Add(control).
Not handling exceptions in event handlers. Use try-catch for user input validation.
Hardcoding control positions. Use TableLayoutPanel or FlowLayoutPanel for responsive layouts.
Ignoring form disposal. Override Dispose() to clean up resources.

Exam Tip

  1. Understand the Lifecycle of a Form:

    • Know the difference between InitializeComponent() (designer-generated) and manual setup in the constructor.
    • Remember that forms are IDisposable—always clean up unmanaged resources.
  2. Event Handling:

    • Questions often test Click, TextChanged, or SelectedIndexChanged events. Practice writing lambda expressions for event handlers.
    • Example:
      btn.Click += (s, e) => { /* Code */ };
      
  3. Layout Management:

    • Use TableLayoutPanel for grid-based layouts and FlowLayoutPanel for dynamic arrangements.
    • Example:
      TableLayoutPanel table = new TableLayoutPanel();
      table.RowCount = 2;
      table.ColumnCount = 2;
      table.Controls.Add(new Label { Text = "Name:" }, 0, 0);
      table.Controls.Add(new TextBox(), 1, 0);
      this.Controls.Add(table);
      
  4. Data Binding:

    • Expect questions on binding ListBox, ComboBox, or DataGridView to collections like List<T> or DataTable.
  5. Real-World Scenarios:

    • Be ready to explain how Windows Forms would be used in a banking app (e.g., loan calculator), e-commerce (e.g., order summary), or utility billing (e.g., NTC/Ncell).

Final Note: Windows Forms is foundational for desktop app development in .NET. Master controls, events, and layout management to build functional UIs. Practice by creating small apps like a To-Do List, Calculator, or Student Record Manager. Good luck!

Based on the TU BITM syllabus for .NET Programming (IT275), unit 5.

Discussion

Loading…