.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:
- Forms: The main window or dialog box (e.g., login screen, calculator).
- Controls: UI elements like buttons, textboxes, labels (added to forms).
- Events: User actions (click, keypress) that trigger code (e.g.,
Button.Click). - Properties: Attributes of controls (e.g.,
Text,Visible,Enabled). - Methods: Code blocks tied to events (e.g.,
button1_Click).
Designing a Windows Form
Step-by-Step Process:
- Create a new WinForms project in Visual Studio:
- File → New → Project → Windows Forms App (.NET Framework).
- 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).
- Drag controls (e.g.,
- 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!");).
- Double-click a control to auto-generate an event method (e.g.,
Example: Simple Calculator Form
Design:
- Add 3
TextBoxcontrols (txtNum1,txtNum2,txtResult). - Add 2
Buttoncontrols (btnAdd,btnSubtract). - Set
Textproperties (e.g.,btnAdd.Text = "Add").
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:
- Anchor: Ties controls to form edges (e.g.,
Anchor = Top, Left). - Dock: Fixes controls to form borders (e.g.,
Dock = Bottom). - FlowLayoutPanel: Arranges controls in a flow (left-to-right, top-to-bottom).
- TableLayoutPanel: Grids controls in rows/columns.
Example: Login Form Layout
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.
Example: Traffic Light Simulator
Design:
- Add 3
PictureBoxcontrols (picRed,picYellow,picGreen) with traffic light images. - Add a
Timercontrol (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:
- Create a data source (e.g.,
List<string> fruits = new List<string> { "Apple", "Banana" };). - Bind to a control:
listBoxFruits.DataSource = fruits; - Update dynamically:
fruits.Add("Orange"); listBoxFruits.Refresh(); // Updates the ListBox
Example: Order Queue for Daraz
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
eSewa (Nepal):
- Uses WinForms-like logic for desktop payment terminals in banks.
- Idea: Event-driven validation (e.g.,
TextChangedin amount fields to check for valid numbers). - How: When a user types an amount in a
TextBox, the system triggerstextBoxAmount_TextChangedto ensure only numbers are entered and auto-calculates fees.
Khalti POS System:
- Idea: Data binding between a
ListBoxof transactions and a backend database. - How: When a merchant scans a QR code, the transaction ID appears in the
ListBoxand is bound to aDataTablefor reporting.
- Idea: Data binding between a
NTC Billing Software:
- Idea: Timer events for auto-updating electricity usage displays.
- How: A
Timertriggers every second to fetch real-time consumption data from a serial port and update aLabelshowing "Current Usage: 5.2 kWh."
Exam Tip
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
TextBoxand shows an error if empty."
Layout Tricks:
- Do: Use
TableLayoutPanelfor grids (e.g., login forms). - Avoid: Absolute positioning (hard to resize).
- Do: Use
Data Binding:
- Key point: Always rebind (
DataSource = null; DataSource = list;) after modifying the data source.
- Key point: Always rebind (
Timer Events:
- Tip: Use
timer1_Tickfor animations or periodic updates (e.g., traffic lights, stock tickers).
- Tip: Use
Trace Tables:
- Practice: For every algorithm, show state changes (e.g.,
TextBoxvalues before/after an event).
- Practice: For every algorithm, show state changes (e.g.,
Common Pitfalls to Avoid
- Forgetting to handle exceptions: Always wrap
Parsemethods (e.g.,double.Parse) intry-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 rebindDataSource. - Ignoring
Dispose(): Clean up resources (e.g.,timer1.Stop(); timer1.Dispose();) inForm_Closing.
Based on the TU BIM syllabus for .NET Programming (IT275), unit 5.
Discussion
Loading…