.NET ProgrammingUnit 59 min read

Windows Forms: Design, Events & Controls

Unit 5 of .NET Programming covers Windows Forms applications in C, including form design, event-driven programming, common controls (buttons, textboxes, lists), layout management, and data binding—essential for building desktop apps with .NET.

What is a Windows Forms Application?

Windows Forms (WinForms) is a graphical user interface (GUI) framework in .NET for building desktop applications with forms, controls, and event-driven logic. It uses drag-and-drop design in Visual Studio and separates UI design from code logic.

Key Components:

  1. Forms: The main window or dialog box (e.g., login screen, calculator).
  2. Controls: UI elements like buttons, textboxes, labels (added to forms).
  3. Events: User actions (click, keypress) that trigger code (e.g., Button.Click).
  4. Properties: Attributes of controls (e.g., Text, Visible, Enabled).
  5. Methods: Code blocks tied to events (e.g., button1_Click).

Designing a Windows Form

Step-by-Step Process:

  1. Create a new WinForms project in Visual Studio:
    • File → New → Project → Windows Forms App (.NET Framework).
  2. Design the form:
    • Drag controls (e.g., Button, TextBox) from the Toolbox onto the form.
    • Adjust properties in the Properties window (e.g., Name, Text, Size).
  3. Write event handlers:
    • Double-click a control to auto-generate an event method (e.g., button1_Click).
    • Add logic inside the method (e.g., MessageBox.Show("Hello!");).

Example: Simple Calculator Form

Design:

  • Add 3 TextBox controls (txtNum1, txtNum2, txtResult).
  • Add 2 Button controls (btnAdd, btnSubtract).
  • Set Text properties (e.g., btnAdd.Text = "Add").
FormTextBoxButton1 (7)Button2 (+)Button3 (=)Label (Result)
Event flow in a calculator: TextBox → Button3 → Label

Code (Event Handlers):

private void btnAdd_Click(object sender, EventArgs e)
{
    double num1 = double.Parse(txtNum1.Text);
    double num2 = double.Parse(txtNum2.Text);
    txtResult.Text = (num1 + num2).ToString();
}

private void btnSubtract_Click(object sender, EventArgs e)
{
    double num1 = double.Parse(txtNum1.Text);
    double num2 = double.Parse(txtNum2.Text);
    txtResult.Text = (num1 - num2).ToString();
}

Trace Table:

Step txtNum1.Text txtNum2.Text txtResult.Text Action
Initial "" "" "" Form loads
User input "10" "5" "" Clicks "Add"
After Add "10" "5" "15" btnAdd_Click runs
After Sub "10" "5" "5" btnSubtract_Click

Common Controls and Their Uses

Control Purpose Key Properties/Events
Button Triggers actions (click) Text, Click event
TextBox Single-line text input/output Text, TextChanged
Label Displays static text Text, AutoSize
ListBox Displays selectable items Items, SelectedIndexChanged
ComboBox Dropdown list + text input Items, SelectedItem
CheckBox Toggle on/off (boolean) Checked, CheckStateChanged
RadioButton Single-choice group Checked, GroupName
PictureBox Displays images Image, SizeMode

Layout Management

WinForms provides auto-layout and manual positioning for controls:

  1. Anchor: Ties controls to form edges (e.g., Anchor = Top, Left).
  2. Dock: Fixes controls to form borders (e.g., Dock = Bottom).
  3. FlowLayoutPanel: Arranges controls in a flow (left-to-right, top-to-bottom).
  4. TableLayoutPanel: Grids controls in rows/columns.

Example: Login Form Layout

Anchor Top, LeftAnchor Top, LeftAnchor Top, LeftAnchor Bottom, RightFormUsername LabelUsername TextBoxPassword TextBoxLogin ButtonForgot Password Link
Login Form Layout with Anchor Properties (Dock not shown; use FlowLayoutPanel/TableLayoutPanel for docking)

Visual: Caption: TableLayoutPanel for a login form (rows=4, columns=2).


Event-Driven Programming

Events are actions (e.g., clicks, keypresses) that trigger event handlers (methods). Common events:

  • Mouse Events: Click, MouseMove, MouseHover.
  • Keyboard Events: KeyPress, KeyDown.
  • Control Events: TextChanged, SelectedIndexChanged.
startUser clicksEvent handler runsRefreshUser closesForm LoadedButton ClickedData UpdatedForm Closed
Event-driven state transitions in WinForms

Example: Traffic Light Simulator

Design:

  • Add 3 PictureBox controls (picRed, picYellow, picGreen) with traffic light images.
  • Add a Timer control (timerLight) set to 2000ms interval.

Code:

private int currentLight = 0; // 0=Red, 1=Yellow, 2=Green

private void timerLight_Tick(object sender, EventArgs e)
{
    picRed.Visible = false;
    picYellow.Visible = false;
    picGreen.Visible = false;

    currentLight = (currentLight + 1) % 3;

    if (currentLight == 0) picRed.Visible = true;
    else if (currentLight == 1) picYellow.Visible = true;
    else picGreen.Visible = true;
}

private void btnStart_Click(object sender, EventArgs e)
{
    timerLight.Start();
}

State After Each Tick: Caption: Traffic light states after each timer tick (cycle repeats).


Data Binding in WinForms

Data binding links UI controls to data sources (e.g., ListBox to a List<string>). Steps:

  1. Create a data source (e.g., List<string> fruits = new List<string> { "Apple", "Banana" };).
  2. Bind to a control:
    listBoxFruits.DataSource = fruits;
    
  3. Update dynamically:
    fruits.Add("Orange");
    listBoxFruits.Refresh(); // Updates the ListBox
    

Example: Order Queue for Daraz

Order10Order21Order32front (processed)rear (new)
Data Binding Example: List<string> orders → ListBox Orders

Code:

List<string> orderQueue = new List<string>();

private void btnAddOrder_Click(object sender, EventArgs e)
{
    orderQueue.Add(txtOrderID.Text);
    listBoxOrders.DataSource = null; // Clear and rebind
    listBoxOrders.DataSource = orderQueue;
}

private void btnProcessOrder_Click(object sender, EventArgs e)
{
    if (orderQueue.Count > 0)
    {
        orderQueue.RemoveAt(0);
        listBoxOrders.DataSource = null;
        listBoxOrders.DataSource = orderQueue;
    }
}

State After Adding/Processing: Caption: Daraz order queue after processing the first order.


In the Real World

  1. eSewa (Nepal):

    • Uses WinForms-like logic for desktop payment terminals in banks.
    • Idea: Event-driven validation (e.g., TextChanged in amount fields to check for valid numbers).
    • How: When a user types an amount in a TextBox, the system triggers textBoxAmount_TextChanged to ensure only numbers are entered and auto-calculates fees.
  2. Khalti POS System:

    • Idea: Data binding between a ListBox of transactions and a backend database.
    • How: When a merchant scans a QR code, the transaction ID appears in the ListBox and is bound to a DataTable for reporting.
  3. NTC Billing Software:

    • Idea: Timer events for auto-updating electricity usage displays.
    • How: A Timer triggers every second to fetch real-time consumption data from a serial port and update a Label showing "Current Usage: 5.2 kWh."

Exam Tip

  1. Design vs. Code:

    • Exam focus: Know how to design a form (drag-and-drop) and write event handlers for common controls.
    • Common question: "Write code for a button that validates a TextBox and shows an error if empty."
  2. Layout Tricks:

    • Do: Use TableLayoutPanel for grids (e.g., login forms).
    • Avoid: Absolute positioning (hard to resize).
  3. Data Binding:

    • Key point: Always rebind (DataSource = null; DataSource = list;) after modifying the data source.
  4. Timer Events:

    • Tip: Use timer1_Tick for animations or periodic updates (e.g., traffic lights, stock tickers).
  5. Trace Tables:

    • Practice: For every algorithm, show state changes (e.g., TextBox values before/after an event).

Common Pitfalls to Avoid

  • Forgetting to handle exceptions: Always wrap Parse methods (e.g., double.Parse) in try-catch.
    try { double num = double.Parse(txtInput.Text); }
    catch { MessageBox.Show("Enter a valid number!"); }
    
  • Not updating UI after data changes: Always call Refresh() or rebind DataSource.
  • Ignoring Dispose(): Clean up resources (e.g., timer1.Stop(); timer1.Dispose();) in Form_Closing.

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

Discussion

Loading…