Dot Net TechnologyUnit 611 min read
WinForms: Controls, Events, MDI, Validation & CRUD Apps
Unit 6 of Dot Net Technology covers Windows Forms (WinForms) programming in C, including controls, events, MDI applications, data validation, and building CRUD (Create, Read, Update, Delete) applications with database integration. This note explains core concepts with visual examples, real-world applications, and step-
TAKEAWAYS:
- WinForms uses drag-and-drop controls (e.g.,
Button,TextBox,DataGridView) bound to events likeClickorTextChangedto create interactive UIs. - MDI (Multiple Document Interface) lets a parent form host multiple child forms, useful for applications like employee management systems.
- Data validation (e.g.,
RequiredFieldValidator,RegularExpressionValidator) ensures user input meets rules before processing. - CRUD operations in WinForms connect to databases via ADO.NET (
SqlConnection,SqlCommand,DataAdapter) to store/retrieve data. - Event-driven programming ties user actions (e.g., button clicks) to code blocks (event handlers) using the
+=operator. - Best practices include separating UI logic from business logic and using
usingblocks for resource cleanup.
1. Introduction to Windows Forms (WinForms)
Windows Forms is a GUI (Graphical User Interface) framework in .NET for building desktop applications. It provides pre-built controls (buttons, text boxes, etc.) and handles user interactions via events.
Key Components
- Controls: UI elements like
Button,TextBox,Label,DataGridView. - Forms: The container for controls (e.g.,
Form1). - Events: Actions triggered by user input (e.g.,
Click,KeyPress). - Properties: Attributes of controls (e.g.,
Text,Visible,Enabled).
How WinForms Works
- Design View: Drag controls onto a form in Visual Studio.
- Event Handling: Double-click a control to auto-generate an event handler (e.g.,
button1_Click). - Code-Behind: Logic is written in
.csfiles (e.g.,Form1.cs).
2. Common WinForms Controls and Their Properties
classDiagram
class Control {
<<abstract>>
+Name: string
+Text: string
+Visible: bool
+Enabled: bool
+Size: Size
+Location: Point
}
class Button {
+Text: string
+Click() Event
}
class TextBox {
+Text: string
+TextChanged() Event
+MaxLength: int
}
class Label {
+Text: string
+AutoSize: bool
}
class DataGridView {
+Columns: DataGridViewColumnCollection
+Rows: DataGridViewRowCollection
+CellClick() Event
}
Control <|-- Button
Control <|-- TextBox
Control <|-- Label
Control <|-- DataGridViewExample: Basic Form with Controls
// Form1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); // Auto-generated by Visual Studio
button1.Text = "Click Me!";
textBox1.Text = "Enter text here...";
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show($"You entered: {textBox1.Text}");
}
}
Visualization: Form Design
3. Event-Driven Programming in WinForms
Events are actions (e.g., clicks, key presses) that trigger code execution. WinForms uses the delegate-event pattern:
- Declare an event in a control (e.g.,
Button.Click). - Subscribe to the event using
+=. - Handle the event in a method.
Example: Event Subscription
// Subscribe to the Click event
button1.Click += Button1_Click;
// Event handler
private void Button1_Click(object sender, EventArgs e)
{
label1.Text = "Button clicked!";
}
Common Events
| Control | Event | Description |
|---|---|---|
Button |
Click |
Triggered when clicked. |
TextBox |
TextChanged |
Fires when text changes. |
DataGridView |
CellClick |
Fires when a cell is clicked. |
Form |
Load |
Runs when the form loads. |
4. MDI (Multiple Document Interface) Applications
MDI allows a parent form to host child forms, useful for applications like:
- Employee Management System (multiple employee records in separate windows).
- Text Editors (e.g., Notepad with multiple open files).
Steps to Create an MDI Application
- Set
IsMdiContainer = truefor the parent form. - Use
MdiParent = thisfor child forms. - Manage child forms via
MdiChildrencollection.
Example: MDI Parent-Child Form
// ParentForm.cs
public partial class ParentForm : Form
{
public ParentForm()
{
InitializeComponent();
this.IsMdiContainer = true;
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
ChildForm child = new ChildForm();
child.MdiParent = this;
child.Show();
}
}
Visualization: MDI Structure
flowchart TD
A["ParentForm\n(IsMdiContainer=true)"] --> B["ChildForm1\n(MdiParent=ParentForm)"]
A --> C["ChildForm2\n(MdiParent=ParentForm)"]
A --> D["ChildForm3\n(MdiParent=ParentForm)"]5. Data Validation in WinForms
Validation ensures user input is correct before processing. Common validators:
RequiredFieldValidator: Checks if a field is empty.RegularExpressionValidator: Validates patterns (e.g., email format).- Custom validation via
ErrorProvider.
Example: Email Validation
private void button1_Click(object sender, EventArgs e)
{
if (!Regex.IsMatch(textBox1.Text, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
{
errorProvider1.SetError(textBox1, "Invalid email format!");
return;
}
MessageBox.Show("Valid email!");
}
Visualization: Validation Flow
flowchart TD
A["User Enters Email"] --> B{"Is Email Valid?"}
B -->|"Yes"| C["Proceed"]
B -->|"No"| D["Show Error\n(errorProvider1)"]6. CRUD Operations in WinForms with ADO.NET
CRUD (Create, Read, Update, Delete) operations connect WinForms to databases using ADO.NET:
SqlConnection: Connects to the database.SqlCommand: Executes SQL queries.SqlDataAdapter: FillsDataTableobjects.DataGridView: Displays data.
Example: Employee CRUD Application
// Connect to database
SqlConnection con = new SqlConnection("Server=.;Database=EmployeeDB;Integrated Security=True;");
con.Open();
// Insert (Create)
SqlCommand cmd = new SqlCommand("INSERT INTO Employees (Name, Salary) VALUES (@Name, @Salary)", con);
cmd.Parameters.AddWithValue("@Name", textBoxName.Text);
cmd.Parameters.AddWithValue("@Salary", textBoxSalary.Text);
cmd.ExecuteNonQuery();
// Read (Retrieve)
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Employees", con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
Visualization: CRUD Workflow
flowchart LR
A["User Input\n(textBox)"] --> B["SqlCommand\n(INSERT/UPDATE/DELETE)"]
C["SqlDataAdapter\n(Fill DataTable)"] --> D["DataGridView\n(Display Data)"]
D -->|"User Edit"| B7. Real-World Applications of WinForms
In the Real World
eSewa (Nepal):
- Uses WinForms-like logic for form validation (e.g., checking mobile number format before processing payments).
- Example: When you enter a wrong mobile number, eSewa shows an error message (similar to
ErrorProviderin WinForms).
Khalti (Nepal):
- MDI-like structure: Multiple transaction windows open in a single parent dashboard.
- Example: After logging in, Khalti shows a main dashboard with child forms for payments, transfers, and profiles.
Banking Applications (e.g., NMB Bank):
- CRUD Operations: WinForms is used internally to manage customer accounts (create, update, delete records).
- Example: When a bank employee updates a loan interest rate, the system uses
SqlCommandto modify the database.
NTC Traffic Management System:
- Event Handling: Traffic lights change based on sensor events (e.g.,
Timer.Tickin WinForms). - Example: A
Timercontrol triggers a red-light display after 30 seconds.
- Event Handling: Traffic lights change based on sensor events (e.g.,
8. Worked Example: Employee Management System
Scenario: Build a WinForms app to manage employees with CRUD operations.
Step-by-Step Implementation
Design the Form:
- Add
TextBoxforName,Salary,Department. - Add
DataGridViewto display records. - Add
Buttons for Add, Update, Delete, View All.
- Add
Database Setup:
CREATE TABLE Employees ( ID INT PRIMARY KEY IDENTITY(1,1), Name NVARCHAR(50), Salary DECIMAL(10,2), Department NVARCHAR(50) );Code for CRUD Operations:
// Add Employee private void btnAdd_Click(object sender, EventArgs e) { SqlCommand cmd = new SqlCommand("INSERT INTO Employees (Name, Salary, Department) VALUES (@Name, @Salary, @Dept)", con); cmd.Parameters.AddWithValue("@Name", txtName.Text); cmd.Parameters.AddWithValue("@Salary", txtSalary.Text); cmd.Parameters.AddWithValue("@Dept", txtDept.Text); cmd.ExecuteNonQuery(); LoadData(); // Refresh DataGridView } // View All Employees private void LoadData() { SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Employees", con); DataTable dt = new DataTable(); da.Fill(dt); dataGridView1.DataSource = dt; }Trace Execution:
Step Action Database State UI State 1 User enters "John", "50000", "IT" No change TextBoxes populated 2 Clicks "Add" Inserts new row: ID=1, Name=John,...DataGridView refreshes 3 User selects row 1 No change Selected row highlights 4 Clicks "Delete" Deletes row ID=1DataGridView updates
Visualization: Database After Insertion
9. Best Practices and Common Pitfalls
Do’s
- Use
usingblocks forSqlConnectionto avoid memory leaks. - Separate UI logic from business logic (e.g., use a
EmployeeServiceclass). - Validate input before database operations.
Don’ts
- Hardcode database credentials in code (use
app.config). - Forget to handle exceptions (e.g.,
SqlException). - Overuse MDI for simple applications (can be slow).
10. Exam Tip
Based on past exam questions, focus on:
MDI Applications:
- Know how to set
IsMdiContainerandMdiParent. - Example: "Create an MDI app with File > New/Close menu items." (4 marks)
- Know how to set
CRUD Operations:
- Be able to write code for insert, update, and delete using
SqlCommand. - Example: "Develop a WinForm app for employee CRUD." (6 marks)
- Be able to write code for insert, update, and delete using
Validation:
- Use
RequiredFieldValidatoror custom validation. - Example: "Write a program to validate an employee registration form." (4 marks)
- Use
Event Handling:
- Explain how
ClickorTextChangedevents work. - Example: "Explain event-driven programming in WinForms." (2 marks)
- Explain how
ADO.NET Basics:
- Differentiate
SqlDataAdapter(fillsDataTable) andSqlDataReader(read-only). - Example: "What are the differences between Data Adapter and Data Reader?" (2 marks)
- Differentiate
Final Note: Always trace your code step-by-step (like the table above) and draw diagrams for MDI or database states. Examiners love visual clarity!
Based on the TU BCA syllabus for Dot Net Technology (CACS408), unit 6.
Discussion
Loading…