.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 : example2. 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 MessageDesigning a Simple Application: Student Grade Calculator
Let’s build a form that calculates the average grade of a student.
Step 1: Create a Form
- Open Visual Studio → Create a Windows Forms App (.NET Framework).
- Design the form with:
- 3
TextBoxcontrols for subject grades. - 1
Buttonto calculate the average. - 1
Labelto display the result.
- 3
Form Layout:
classDiagram
class Form {
+TextBox[] Grades
+Button Calculate
+Label Result
}
Form --> TextBox : 3 subjects
Form --> Button : Calculate
Form --> Label : ResultStep 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
- Press F5 to run.
- Enter grades in the textboxes and click Calculate Average.
- 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
eSewa (Nepal)
- Use of Windows Forms: Older versions of eSewa’s desktop client used Windows Forms for local bill payments and transaction history. The
ListBoxcontrol displayed transaction records, andButtonevents triggered payments. - Example: When a user clicks the "Pay Bill" button, the
Clickevent handler validates input (e.g., phone number, amount) and processes the payment via eSewa’s API.
- Use of Windows Forms: Older versions of eSewa’s desktop client used Windows Forms for local bill payments and transaction history. The
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
TextBoxcaptures the loan amount, interest rate, and tenure, while aButtontriggers the calculation. The result (monthly installment) is displayed in aLabel. - Example: If a user enters:
- Loan Amount: 5,00,000
- Interest Rate: 8%
- Tenure: 5 years
The
Calculatebutton’s event handler computes EMI using the formula: where , , .
- Use of Windows Forms: Banks use Windows Forms apps for internal tools like loan calculators. A
NTC’s Billing System (Older Versions)
- Use of Windows Forms: NTC’s legacy billing software used Windows Forms for generating and printing bills. A
ComboBoxallowed users to select customer IDs, while aButtongenerated the bill and displayed it in aRichTextBoxbefore printing.
- Use of Windows Forms: NTC’s legacy billing software used Windows Forms for generating and printing bills. A
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 Automatically3. 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
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.
- Know the difference between
Event Handling:
- Questions often test
Click,TextChanged, orSelectedIndexChangedevents. Practice writing lambda expressions for event handlers. - Example:
btn.Click += (s, e) => { /* Code */ };
- Questions often test
Layout Management:
- Use
TableLayoutPanelfor grid-based layouts andFlowLayoutPanelfor 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);
- Use
Data Binding:
- Expect questions on binding
ListBox,ComboBox, orDataGridViewto collections likeList<T>orDataTable.
- Expect questions on binding
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…