CACS408 Dot Net Technology

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 like Click or TextChanged to 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 using blocks 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

  1. Design View: Drag controls onto a form in Visual Studio.
  2. Event Handling: Double-click a control to auto-generate an event handler (e.g., button1_Click).
  3. Code-Behind: Logic is written in .cs files (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 <|-- DataGridView

Example: 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:

  1. Declare an event in a control (e.g., Button.Click).
  2. Subscribe to the event using +=.
  3. 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

  1. Set IsMdiContainer = true for the parent form.
  2. Use MdiParent = this for child forms.
  3. Manage child forms via MdiChildren collection.

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: Fills DataTable objects.
  • 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"| B

7. Real-World Applications of WinForms

In the Real World

  1. 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 ErrorProvider in WinForms).
  2. 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.
  3. 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 SqlCommand to modify the database.
  4. NTC Traffic Management System:

    • Event Handling: Traffic lights change based on sensor events (e.g., Timer.Tick in WinForms).
    • Example: A Timer control triggers a red-light display after 30 seconds.

8. Worked Example: Employee Management System

Scenario: Build a WinForms app to manage employees with CRUD operations.

Step-by-Step Implementation

  1. Design the Form:

    • Add TextBox for Name, Salary, Department.
    • Add DataGridView to display records.
    • Add Buttons for Add, Update, Delete, View All.
  2. Database Setup:

    CREATE TABLE Employees (
        ID INT PRIMARY KEY IDENTITY(1,1),
        Name NVARCHAR(50),
        Salary DECIMAL(10,2),
        Department NVARCHAR(50)
    );
    
  3. 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;
    }
    
  4. 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=1 DataGridView updates

Visualization: Database After Insertion


9. Best Practices and Common Pitfalls

Do’s

  • Use using blocks for SqlConnection to avoid memory leaks.
  • Separate UI logic from business logic (e.g., use a EmployeeService class).
  • 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:

  1. MDI Applications:

    • Know how to set IsMdiContainer and MdiParent.
    • Example: "Create an MDI app with File > New/Close menu items." (4 marks)
  2. CRUD Operations:

    • Be able to write code for insert, update, and delete using SqlCommand.
    • Example: "Develop a WinForm app for employee CRUD." (6 marks)
  3. Validation:

    • Use RequiredFieldValidator or custom validation.
    • Example: "Write a program to validate an employee registration form." (4 marks)
  4. Event Handling:

    • Explain how Click or TextChanged events work.
    • Example: "Explain event-driven programming in WinForms." (2 marks)
  5. ADO.NET Basics:

    • Differentiate SqlDataAdapter (fills DataTable) and SqlDataReader (read-only).
    • Example: "What are the differences between Data Adapter and Data Reader?" (2 marks)

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…