0% found this document useful (0 votes)
4 views98 pages

Windows Programing

The document provides a comprehensive guide to Visual Programming with Windows Forms, covering topics such as the introduction to Windows Forms, UI controls, and their properties. It includes detailed sections on adding controls, working with DataTables and DataGridViews, and utilizing dialogs. The content is structured to assist users in understanding and implementing visual programming concepts effectively.

Uploaded by

tanveerashfaq177
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views98 pages

Windows Programing

The document provides a comprehensive guide to Visual Programming with Windows Forms, covering topics such as the introduction to Windows Forms, UI controls, and their properties. It includes detailed sections on adding controls, working with DataTables and DataGridViews, and utilizing dialogs. The content is structured to assist users in understanding and implementing visual programming concepts effectively.

Uploaded by

tanveerashfaq177
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Visual Programming with Windows Forms

Muhammad Nadeem
2
Contents

1 Introduction to Windows Forms 7


1.1 What is Visual Programming? . . . . . . . . . . . . . . . . . . . . . . . . 7
1.2 What are Forms? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.2.1 Key Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.2.2 Purpose of Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.3 UI Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.3.1 Common UI Controls in C# . . . . . . . . . . . . . . . . . . . . . 8
1.3.2 Properties, Events, and Methods . . . . . . . . . . . . . . . . . . 9
1.3.3 Delegates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3.4 Importance in Event-Driven Programming . . . . . . . . . . . . . 9
1.4 Adding Controls in Windows Forms . . . . . . . . . . . . . . . . . . . . . 9
1.4.1 Using the Visual Studio Designer . . . . . . . . . . . . . . . . . . 9
1.4.2 Adding Controls Programmatically . . . . . . . . . . . . . . . . . 10
1.4.3 General Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2 UI Controls and Their Properties 11


2.1 Control Hierarchy and Common Properties . . . . . . . . . . . . . . . . . 11
2.1.1 Core Properties Common to Most Controls . . . . . . . . . . . . . 11
2.2 Basic Input Controls in Depth . . . . . . . . . . . . . . . . . . . . . . . . 12
2.2.1 Button Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.2.2 TextBox Control . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2.3 Label Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2.4 CheckBox Control . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2.5 RadioButton Control . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2.6 ComboBox Control . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.7 ListBox Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.2.8 PictureBox Control . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.2.9 ProgressBar Control . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.2.10 DataGridView Control . . . . . . . . . . . . . . . . . . . . . . . . 23
2.3 Container Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.3.1 Panel Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.3.2 GroupBox Control . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.3.3 TabControl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.3.4 SplitContainer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.4 Menu and Toolbar Controls . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.4.1 MenuStrip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.4.2 ToolStrip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.4.3 StatusStrip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

3
4 CONTENTS

2.5 Working with Control Collections . . . . . . . . . . . . . . . . . . . . . . 36


2.5.1 Common Controls Collection Operations . . . . . . . . . . . . . . 36
2.5.2 Container Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.6 Best Practices for Control Usage . . . . . . . . . . . . . . . . . . . . . . . 37
2.6.1 Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.6.2 Layout Considerations . . . . . . . . . . . . . . . . . . . . . . . . 37
2.7 Student Information Management System . . . . . . . . . . . . . . . . . 38
2.7.1 Project Description . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.7.2 Complete Code Implementation . . . . . . . . . . . . . . . . . . . 38
2.7.3 How to Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

3 DataTable and DataGridView 59


3.1 Introduction to DataTable . . . . . . . . . . . . . . . . . . . . . . . . . . 59
3.1.1 Core Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
3.1.2 Creating and Populating a DataTable . . . . . . . . . . . . . . . . 59
3.1.3 Accessing and Modifying Data . . . . . . . . . . . . . . . . . . . . 60
3.1.4 Common Operations . . . . . . . . . . . . . . . . . . . . . . . . . 60
3.1.5 Binding a DataTable to UI Controls . . . . . . . . . . . . . . . . 60
3.2 DataGridView Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
3.2.1 Cell Interaction Events . . . . . . . . . . . . . . . . . . . . . . . . 61
3.2.2 Cell Editing Events . . . . . . . . . . . . . . . . . . . . . . . . . . 61
3.2.3 Row Interaction Events . . . . . . . . . . . . . . . . . . . . . . . . 62
3.2.4 Column and Header Events . . . . . . . . . . . . . . . . . . . . . 62
3.2.5 Data Binding and Error Events . . . . . . . . . . . . . . . . . . . 62
3.3 DataGridView Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
3.3.1 Column Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
3.3.2 Adding Columns Programmatically . . . . . . . . . . . . . . . . . 63
3.3.3 Key Column Properties . . . . . . . . . . . . . . . . . . . . . . . 63
3.4 Customizing DataGridView . . . . . . . . . . . . . . . . . . . . . . . . . 64
3.4.1 Styling Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
3.4.2 Conditional Formatting . . . . . . . . . . . . . . . . . . . . . . . 64
3.4.3 Editing Customization . . . . . . . . . . . . . . . . . . . . . . . . 65

4 Dialogs 67
4.1 Dialogs in Windows Forms . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.2 MessageBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.2.1 Basic Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.2.2 Form as Dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.3 Common Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
4.3.1 OpenFileDialog and SaveFileDialog . . . . . . . . . . . . . . . . . 68
4.3.2 FontDialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.3.3 ColorDialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.3.4 Print Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
4.4 Text Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
4.4.1 Project Description . . . . . . . . . . . . . . . . . . . . . . . . . . 70
4.4.2 Complete Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
4.4.3 How to Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
CONTENTS 5

5 Drawing and Mouse Interactions 81


5.1 Introduction to Drawing in Windows Forms . . . . . . . . . . . . . . . . 81
5.1.1 What is Drawing? . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.1.2 Key Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.2 Drawing Rectangles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.2.1 DrawRectangle (Outline) . . . . . . . . . . . . . . . . . . . . . . . 81
5.2.2 FillRectangle (Solid) . . . . . . . . . . . . . . . . . . . . . . . . . 82
5.2.3 Brush Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
5.3 Drawing Ellipses and Circles . . . . . . . . . . . . . . . . . . . . . . . . . 83
5.3.1 DrawEllipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
5.4 Drawing Polygons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
5.5 Mouse Interactions for Drawing . . . . . . . . . . . . . . . . . . . . . . . 84
5.5.1 Mouse Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
5.5.2 Common Applications . . . . . . . . . . . . . . . . . . . . . . . . 84
5.5.3 Important Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

6 Interacting with Databases using C# 85


6.1 Introduction to Databases . . . . . . . . . . . . . . . . . . . . . . . . . . 85
6.1.1 Core Components . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
6.1.2 Why Applications Need Databases . . . . . . . . . . . . . . . . . 85
6.1.3 Local vs. Remote Databases . . . . . . . . . . . . . . . . . . . . . 85
6.2 [Link]: Bridge Between C# and Databases . . . . . . . . . . . . . . 86
6.2.1 Key [Link] Classes . . . . . . . . . . . . . . . . . . . . . . . . 86
6.3 Connecting to a Database . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.3.1 Connection Strings . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.4 Executing SQL Commands . . . . . . . . . . . . . . . . . . . . . . . . . . 87
6.4.1 INSERT, UPDATE, DELETE Operations . . . . . . . . . . . . . 87
6.4.2 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . 88
6.5 Reading Data (SELECT Queries) . . . . . . . . . . . . . . . . . . . . . . 88
6.5.1 Using SqlDataReader (Row-by-Row) . . . . . . . . . . . . . . . . 88
6.5.2 Loading Data into DataTable . . . . . . . . . . . . . . . . . . . . 88
6.5.3 Displaying Data in DataGridView . . . . . . . . . . . . . . . . . . 89
6.6 Parameterized Queries (Security Critical) . . . . . . . . . . . . . . . . . . 89
6.6.1 Preventing SQL Injection . . . . . . . . . . . . . . . . . . . . . . 89
6.6.2 Parameter Data Types . . . . . . . . . . . . . . . . . . . . . . . . 90
6.7 Updating UI from Database . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.7.1 Refreshing Data After Operations . . . . . . . . . . . . . . . . . . 90
6.8 Data Binding with Windows Forms Controls . . . . . . . . . . . . . . . . 90
6.8.1 Binding ComboBox and ListBox . . . . . . . . . . . . . . . . . . . 90
6.8.2 Binding DataGridView . . . . . . . . . . . . . . . . . . . . . . . . 91
6.9 Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.9.1 Always Close Connections (Using Blocks) . . . . . . . . . . . . . 91
6.9.2 Connection Pooling . . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.9.3 Principle of Least Privilege . . . . . . . . . . . . . . . . . . . . . . 92
6.10 Async Database Operations . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.10.1 Keeping UI Responsive . . . . . . . . . . . . . . . . . . . . . . . . 92
6.11 Master-Detail Relationship . . . . . . . . . . . . . . . . . . . . . . . . . . 93
6 CONTENTS

7 Libraries in C# 95
7.1 Introduction to Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
7.1.1 Types of Libraries in .NET . . . . . . . . . . . . . . . . . . . . . . 95
7.2 Dynamic Link Libraries (DLLs) . . . . . . . . . . . . . . . . . . . . . . . 95
7.2.1 Creating a DLL . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
7.2.2 Using a DLL in Another Project . . . . . . . . . . . . . . . . . . . 96
7.2.3 DLL Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
7.3 Static Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
7.4 NuGet Packages: Third-Party Libraries . . . . . . . . . . . . . . . . . . . 97
7.4.1 Installing NuGet Packages . . . . . . . . . . . . . . . . . . . . . . 97
7.4.2 Example: Using [Link] . . . . . . . . . . . . . . . . . . 97
7.4.3 Popular NuGet Packages . . . . . . . . . . . . . . . . . . . . . . . 98
7.4.4 Managing NuGet Packages . . . . . . . . . . . . . . . . . . . . . . 98
7.5 Best Practices for Using Libraries . . . . . . . . . . . . . . . . . . . . . . 99
Chapter 1

Introduction to Windows Forms

1.1 What is Visual Programming?


Visual programming uses graphical elements to build software interfaces and logic. In
C# Windows Forms, developers place and configure controls like buttons and textboxes
through a visual designer while maintaining full control via code.
This approach enables:

ˆ Dynamic form creation through code


ˆ Programmatic control placement and customization
ˆ Event-driven user interaction handling
1.2 What are Forms?
Forms are visual containers that host interactive elements like buttons and text boxes.
They serve as windows or dialog boxes that users interact with, providing structure for
an application’s interface.

1.2.1 Key Characteristics


ˆ Visual Boundary: Defines a distinct screen area with title bar, borders, and
window controls

ˆ Container for Controls: Hosts UI elements that enable user interaction and data
display

ˆ Event Handling: Responds to events like loading, closing, resizing, and mouse
interactions

ˆ Layout Management: Automatically arranges controls using docking, anchoring,


or layout managers

ˆ User Interaction Point: Primary interface for user input and output
7
8 CHAPTER 1. INTRODUCTION TO WINDOWS FORMS

1.2.2 Purpose of Forms


ˆ Organize UI Elements: Group related controls for logical, intuitive navigation
ˆ Present Information: Display data through labels, text boxes, grids, and other
elements

ˆ Gather User Input: Collect data via text fields, dropdowns, checkboxes, and
input controls

ˆ Implement Application Logic: Execute behavior through event handlers re-


sponding to user actions

ˆ Create Various Interface Types: Build main windows, dialog boxes, wizards,
and more

1.3 UI Controls
UI controls are interactive elements enabling users to input data, trigger actions, and
view information. Forms serve as containers that host and arrange these components.
GUI frameworks like Windows Forms provide extensive pre-built control libraries.

1.3.1 Common UI Controls in C#


C# offers built-in controls essential for constructing Windows desktop application inter-
faces.

Basic Input Controls


ˆ Button: Triggers actions via Click event handlers
ˆ TextBox: Captures editable text; Text property stores content; TextChanged event
tracks modifications

ˆ Label: Displays non-editable static text for captions or output


ˆ CheckBox: Represents binary choice; Checked property indicates state; CheckedChanged
event responds to toggles

ˆ RadioButton: Enables mutually exclusive selection within a container; uses Checked


property and CheckedChanged event

ˆ ComboBox: Dropdown list for single selection; SelectedItem/SelectedIndex re-


trieve values; SelectedIndexChanged handles changes

ˆ ListBox: Displays selectable items (single or multiple); uses SelectedItem/SelectedItems


and corresponding change events

ˆ PictureBox: Renders images via Image property


ˆ ProgressBar: Shows operation progress; Value property controls visual state
ˆ DataGridView: Displays and edits tabular data with extensive customization
1.4. ADDING CONTROLS IN WINDOWS FORMS 9

Container and Layout Controls


ˆ Panel: Groups controls for organization and applying shared properties
ˆ GroupBox: Panel variant with titled border for visually related controls
ˆ TabControl: Organizes multiple panels into switchable tabs
Navigation and Menu Controls
ˆ MenuStrip: Creates hierarchical application menus at form top
ˆ ToolStrip: Provides toolbar with quick-access command buttons
ˆ StatusBar: Displays status information at form bottom
These controls form the foundation for diverse desktop applications. Selection depends
on application requirements and desired user experience.

1.3.2 Properties, Events, and Methods


Each control includes properties defining appearance and behavior (e.g., text, color, size,
visibility). Controls raise events responding to user actions (e.g., Click, TextChanged).
Developers implement application logic through event handlers. Methods enable pro-
grammatic manipulation of control state.

1.3.3 Delegates
Delegates are type-safe function pointers that define the signature of a method that can
be invoked through them. They enable methods to be passed as parameters, allowing for
flexible and extensible code.

1.3.4 Importance in Event-Driven Programming


UI controls are central to event-driven programming. User interactions generate events,
and application logic executes through corresponding event handlers. This paradigm
enables responsive, interactive applications. Developers primarily configure control prop-
erties and implement event handlers to define behavior based on user interactions.

1.4 Adding Controls in Windows Forms


Windows Forms development involves adding UI controls to forms either through Visual
Studio’s visual designer or programmatically for dynamic scenarios.

1.4.1 Using the Visual Studio Designer


The designer provides an intuitive drag-and-drop interface:

1. Open Form in Design View: Double-click the form’s ‘.cs’ file (e.g., [Link])
in Solution Explorer
10 CHAPTER 1. INTRODUCTION TO WINDOWS FORMS

2. Access Toolbox: Open via View → Toolbox or Ctrl+Alt+X

3. Select Controls: Browse categorized controls in the Toolbox

4. Drag and Drop: Click and drag controls from Toolbox onto the form surface

5. Position and Size: Move by dragging; resize using sizing handles

6. Set Properties: Use the Properties window (View → Properties Window or


F4) to modify attributes like Text, Name, BackColor, and Font

The designer automatically generates the corresponding C# code in the form’s ‘.De-
[Link]’ file.

1.4.2 Adding Controls Programmatically


Programmatic addition is essential when controls must be created dynamically based on
runtime conditions.

1.4.3 General Syntax


// 1. Create control instance
ControlType controlName = new ControlType();

// 2. Set properties (Location, Size, Text, Name, etc.)


controlName.Property1 = value1;
controlName.Property2 = value2;

// 3. Attach event handlers (optional)


[Link] += HandlerMethod;

// 4. Add to form’s Controls collection


[Link](controlName);
Chapter 2

UI Controls and Their Properties

2.1 Control Hierarchy and Common Properties


All Windows Forms controls inherit from the [Link] class,
which provides a set of base properties, methods, and events shared across all controls.

2.1.1 Core Properties Common to Most Controls

Property Description Typical Usage


Name Identifier used to reference the Set in designer; used program-
control in code matically to access the control
Text The text displayed on/in the con- Button labels, textbox content,
trol form titles
Location Position (X, Y coordinates) rela- Set via designer or programmati-
tive to container cally for dynamic positioning
Size Width and height of the control Defines control dimensions
BackColor Background color Visual styling, indicating state
ForeColor Foreground/text color Readability and visual feedback
Font Font family, size, and style Text appearance customization
Enabled Whether the control can respond Disabling controls when condi-
to user interaction tions aren’t met
Visible Whether the control is displayed Showing/hiding elements dynam-
ically
Anchor Which edges of the container the Maintaining control position dur-
control binds to ing form resizing
Dock Which edge of the container the Creating layouts (e.g., toolbar at
control attaches to top, status bar at bottom)
Tag Holds custom data associated Storing additional information
with the control without subclassing

Table 2.1: Common properties inherited from the Control class

1 // Creating a button with various common properties


2 Button exampleButton = new Button () ;
3 exampleButton . Name = " btnSubmit " ; // Identifier

11
12 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

4 exampleButton . Text = " Click Me " ; // Display text


5 exampleButton . Location = new Point (50 , 50) ; // Position
6 exampleButton . Size = new Size (120 , 30) ; // Dimensions
7 exampleButton . BackColor = Color . LightBlue ; // Background
8 exampleButton . ForeColor = Color . Black ; // Text color
9 exampleButton . Font = new Font ( " Arial " , 10 , FontStyle . Bold ) ;
10 exampleButton . Enabled = true ; // Interactive
11 exampleButton . Visible = true ; // Visible
12 exampleButton . Anchor = AnchorStyles . Top | AnchorStyles . Left ; //
Anchor to top - left
13 exampleButton . Tag = " user - data " ; // Custom data
Listing 2.1: Demonstrating common properties in code

2.2 Basic Input Controls in Depth


2.2.1 Button Control
The Button control triggers actions when clicked—the most fundamental interaction in
GUI applications.
Key Properties:

ˆ Text: Button label


ˆ FlatStyle: Visual style (Standard, Flat, Popup, System)
ˆ Image: Optional icon displayed on button
ˆ ImageAlign: Position of image relative to text
ˆ DialogResult: Predefined return value when used in dialog boxes
Primary Event:

ˆ Click: Fires when button is clicked (most commonly handled)


Example:
1 Button submitButton = new Button () ;
2 submitButton . Text = " Submit " ;
3 submitButton . Location = new Point (50 , 100) ;
4 submitButton . Size = new Size (100 , 30) ;
5 submitButton . BackColor = Color . LightGreen ;
6 submitButton . FlatStyle = FlatStyle . Popup ;
7 submitButton . Image = Image . FromFile ( " submit_icon . png " ) ;
8 submitButton . ImageAlign = ContentAlignment . MiddleLeft ;
9 submitButton . Click += Sub mi tB ut to n_ Cl ic k ;
10
11 // Event handler implementation
12 private void S ub mi tB ut to n_ Cl ic k ( object sender , EventArgs e )
13 {
14 MessageBox . Show ( " Button was clicked ! " ) ;
15 }
Listing 2.2: Creating a Button programmatically
2.2. BASIC INPUT CONTROLS IN DEPTH 13

2.2.2 TextBox Control


The TextBox control captures text input from users.
Key Properties:

Property Description
Text Current content of the textbox
MaxLength Maximum number of characters allowed (0 = unlimited)
Multiline Allows multiple lines of text when true
PasswordChar Character displayed instead of actual text (for pass-
words)
ReadOnly Prevents editing while allowing selection/copying
WordWrap Wraps text to next line in multiline mode
ScrollBars Adds scrollbars to multiline textboxes
TextAlign Horizontal alignment of text (Left, Center, Right)
CharacterCasing Automatically converts input to Upper or Lower case

Table 2.2: Key properties of the TextBox control

Key Events:
ˆ TextChanged: Fires whenever text content changes
ˆ Enter/Leave: Fires when control gains/loses focus
ˆ Validating/Validated: Used for input validation
Example:
1 // Single - line textbox for name input
2 TextBox nameTextBox = new TextBox () ;
3 nameTextBox . Location = new Point (120 , 30) ;
4 nameTextBox . Size = new Size (200 , 20) ;
5 nameTextBox . MaxLength = 50;
6 nameTextBox . TextChanged += N a m e T e x t B o x _ T e x t C h a n g e d ;
7
8 // Password textbox
9 TextBox passwordTextBox = new TextBox () ;
10 passwordTextBox . Location = new Point (120 , 60) ;
11 passwordTextBox . Size = new Size (200 , 20) ;
12 passwordTextBox . PasswordChar = ’* ’;
13 passwordTextBox . MaxLength = 20;
14
15 // Multi - line textbox for comments
16 TextBox commentsTextBox = new TextBox () ;
17 commentsTextBox . Location = new Point (120 , 90) ;
18 commentsTextBox . Size = new Size (200 , 80) ;
19 commentsTextBox . Multiline = true ;
20 commentsTextBox . ScrollBars = ScrollBars . Vertical ;
21 commentsTextBox . WordWrap = true ;
22
23 // Validation example
24 private void n a m e T e x t B o x _ V a l i d a t i n g ( object sender , CancelEventArgs e )
25 {
26 TextBox tb = sender as TextBox ;
27 if ( string . I sN ul lO rW hi te Sp ac e ( tb . Text ) )
14 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

28 {
29 MessageBox . Show ( " Name cannot be empty ! " ) ;
30 e . Cancel = true ; // Prevents focus from leaving
31 }
32 }
Listing 2.3: Creating different types of TextBoxes

2.2.3 Label Control


The Label control displays static text that users cannot edit.
Key Properties:
ˆ Text: Content to display
ˆ AutoSize: Automatically adjusts size to fit content
ˆ TextAlign: Alignment of text within label bounds
ˆ BorderStyle: Optional border (None, FixedSingle, Fixed3D)
Example:
1 // Simple label
2 Label instructionLabel = new Label () ;
3 instructionLabel . Text = " Please enter your name : " ;
4 instructionLabel . Location = new Point (20 , 30) ;
5 instructionLabel . AutoSize = true ;
6
7 // Styled label with border
8 Label resultLabel = new Label () ;
9 resultLabel . Text = " Result will appear here " ;
10 resultLabel . Location = new Point (20 , 150) ;
11 resultLabel . Size = new Size (200 , 30) ;
12 resultLabel . BorderStyle = BorderStyle . FixedSingle ;
13 resultLabel . TextAlign = ContentAlignment . MiddleCenter ;
14 resultLabel . BackColor = Color . LightYellow ;
15

16 // LinkLabel ( specialized label for hyperlinks )


17 LinkLabel linkLabel = new LinkLabel () ;
18 linkLabel . Text = " Visit our website " ;
19 linkLabel . Location = new Point (20 , 200) ;
20 linkLabel . AutoSize = true ;
21 linkLabel . LinkClicked += (s , e ) = > {
22 System . Diagnostics . Process . Start ( " https :// example . com " ) ;
23 };
Listing 2.4: Creating Labels

2.2.4 CheckBox Control


The CheckBox control presents a binary choice or multiple independent options.
Key Properties:
ˆ Checked: Boolean value indicating whether box is checked
ˆ CheckState: Three-state value (Checked, Unchecked, Indeterminate)
2.2. BASIC INPUT CONTROLS IN DEPTH 15

ˆ ThreeState: Enables indeterminate state when true


ˆ Appearance: Normal or Button-like appearance
ˆ TextAlign: Position of text relative to checkbox
Key Events:
ˆ CheckedChanged: Fires when Checked property changes
ˆ CheckStateChanged: Fires when CheckState changes (includes indeterminate)
Example:
1 // Standard checkbox
2 CheckBox agreeCheckBox = new CheckBox () ;
3 agreeCheckBox . Text = " I agree to the terms and conditions " ;
4 agreeCheckBox . Location = new Point (20 , 30) ;
5 agreeCheckBox . Size = new Size (250 , 20) ;
6 agreeCheckBox . CheckedChanged += A g r e e C h e c k B o x _ C h e c k e d C h a n g e d ;
7
8 // Three - state checkbox
9 CheckBox featureCheckBox = new CheckBox () ;
10 featureCheckBox . Text = " Enable advanced features " ;
11 featureCheckBox . Location = new Point (20 , 60) ;
12 featureCheckBox . ThreeState = true ;
13 featureCheckBox . CheckState = CheckState . Indeterminate ; // Initial
state
14

15 // Button - like checkbox


16 CheckBox toggleButton = new CheckBox () ;
17 toggleButton . Text = " Toggle Sound " ;
18 toggleButton . Location = new Point (20 , 90) ;
19 toggleButton . Appearance = Appearance . Button ;
20 toggleButton . Size = new Size (100 , 30) ;
21
22 private void A g r e e C h e c k B o x _ C h e c k e d C h a n g e d ( object sender , EventArgs e )
23 {
24 CheckBox chk = sender as CheckBox ;
25 submitButton . Enabled = chk . Checked ; // Enable submit only if agreed
26 }
Listing 2.5: Working with CheckBoxes

2.2.5 RadioButton Control


The RadioButton control presents mutually exclusive options within a group.
Key Properties:
ˆ Checked: Boolean indicating selection
ˆ Appearance: Normal or Button-like
ˆ AutoCheck: Automatically handles mutual exclusivity when true
Key Events:
ˆ CheckedChanged: Fires when selection changes
16 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

Grouping Behavior: All radio buttons within the same container (Form, Panel,
GroupBox) form a group. Only one can be selected at a time.
Example:
1 // First group - Payment method ( directly on form )
2 RadioButton cashRadio = new RadioButton () ;
3 cashRadio . Text = " Cash " ;
4 cashRadio . Location = new Point (20 , 30) ;
5 cashRadio . Checked = true ;
6
7 RadioButton cardRadio = new RadioButton () ;
8 cardRadio . Text = " Credit Card " ;
9 cardRadio . Location = new Point (20 , 55) ;
10
11 RadioButton upiRadio = new RadioButton () ;
12 upiRadio . Text = " UPI " ;
13 upiRadio . Location = new Point (20 , 80) ;
14
15 // Second group - Delivery options ( inside GroupBox )
16 GroupBox deliveryGroup = new GroupBox () ;
17 deliveryGroup . Text = " Delivery Method " ;
18 deliveryGroup . Location = new Point (20 , 120) ;
19 deliveryGroup . Size = new Size (200 , 100) ;
20
21 RadioButton standardDelivery = new RadioButton () ;
22 standardDelivery . Text = " Standard (3 -5 days ) " ;
23 standardDelivery . Location = new Point (10 , 20) ;
24 standardDelivery . Checked = true ;
25
26 RadioButton expressDelivery = new RadioButton () ;
27 expressDelivery . Text = " Express (1 -2 days ) " ;
28 expressDelivery . Location = new Point (10 , 45) ;
29
30 deliveryGroup . Controls . Add ( standardDelivery ) ;
31 deliveryGroup . Controls . Add ( expressDelivery ) ;
32 this . Controls . Add ( deliveryGroup ) ;
33

34 // Event handler
35 private void R a d i o B u t t o n _ C h e c k e d C h a n g e d ( object sender , EventArgs e )
36 {
37 RadioButton rb = sender as RadioButton ;
38 if ( rb . Checked )
39 {
40 MessageBox . Show ( $ " Selected : { rb . Text } " ) ;
41 }
42 }
Listing 2.6: Creating RadioButton groups

2.2.6 ComboBox Control


The ComboBox combines a text box with a dropdown list.
Key Properties:
DropDownStyle Values:

ˆ Simple: List always visible, editable text


2.2. BASIC INPUT CONTROLS IN DEPTH 17

Property Description
Items Collection of items in the list
DropDownStyle Simple, DropDown, or DropDownList
SelectedItem Currently selected object
SelectedIndex Zero-based index of selected item (-1 if none)
SelectedText Text of selected item
MaxDropDownItems Maximum number visible in dropdown
AutoCompleteMode Suggest/append auto-completion

Table 2.3: Key properties of the ComboBox control

ˆ DropDown: Dropdown list, editable text (default)


ˆ DropDownList: Dropdown list, non-editable text
Key Events:

ˆ SelectedIndexChanged: Fires when selection changes


ˆ DropDown/DropDownClosed: Fires when list opens/closes
Example:
1 // DropDownList style ( non - editable )
2 ComboBox countryCombo = new ComboBox () ;
3 countryCombo . Location = new Point (120 , 60) ;
4 countryCombo . Size = new Size (150 , 21) ;
5 countryCombo . DropDownStyle = ComboBoxStyle . DropDownList ;
6 countryCombo . Items . AddRange ( new string [] { " USA " , " Canada " , " UK " , "
Australia " }) ;
7 countryCombo . SelectedIndex = 0; // Select first item
8 countryCombo . S e l e c t e d I n d e x C h a n g e d +=
CountryCombo_SelectedIndexChanged ;
9
10 // DropDown style ( editable )
11 ComboBox colorCombo = new ComboBox () ;
12 colorCombo . Location = new Point (120 , 90) ;
13 colorCombo . Size = new Size (150 , 21) ;
14 colorCombo . DropDownStyle = ComboBoxStyle . DropDown ;
15 colorCombo . Items . AddRange ( new string [] { " Red " , " Green " , " Blue " , "
Yellow " }) ;
16 colorCombo . AutoCompleteMode = AutoCompleteMode . SuggestAppend ;
17
18 // Simple style ( always visible )
19 ComboBox fontCombo = new ComboBox () ;
20 fontCombo . Location = new Point (120 , 120) ;
21 fontCombo . Size = new Size (150 , 100) ; // Taller to show list
22 fontCombo . DropDownStyle = ComboBoxStyle . Simple ;
23 fontCombo . Items . AddRange ( new string [] { " Arial " , " Times New Roman " , "
Courier New " , " Verdana " }) ;
24
25 // Adding objects instead of strings
26 ComboBox userCombo = new ComboBox () ;
27 userCombo . Location = new Point (120 , 150) ;
28 userCombo . Size = new Size (150 , 21) ;
29 userCombo . DisplayMember = " Name " ; // Property to display
18 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

30 userCombo . ValueMember = " Id " ; // Property for value


31 userCombo . Items . Add ( new User { Id = 1 , Name = " John Doe " }) ;
32 userCombo . Items . Add ( new User { Id = 2 , Name = " Jane Smith " }) ;
33
34 private void C o u n t r y C o m b o _ S e l e c t e d I n d e x C h a n g e d ( object sender ,
EventArgs e )
35 {
36 ComboBox combo = sender as ComboBox ;
37 string selectedCountry = combo . SelectedItem . ToString () ;
38 MessageBox . Show ( $ " You selected : { selectedCountry } " ) ;
39 }
40
41 // Custom class for combo items
42 public class User
43 {
44 public int Id { get ; set ; }
45 public string Name { get ; set ; }
46 }
Listing 2.7: Creating different ComboBox styles

2.2.7 ListBox Control


The ListBox displays a scrollable list of items for selection.
Key Properties:

Property Description
Items Collection of items in the list
SelectionMode One, MultiSimple, or MultiExtended
SelectedItem First selected item
SelectedItems Collection of all selected items
SelectedIndex Index of first selected item
SelectedIndices Collection of selected indices
Sorted Automatically sorts items alphabetically
ColumnWidth For multi-column lists

Table 2.4: Key properties of the ListBox control

SelectionMode Values:
ˆ None: No selection allowed
ˆ One: Single selection only
ˆ MultiSimple: Multiple selection via click/toggle
ˆ MultiExtended: Multiple selection with Ctrl/Shift modifiers
Key Events:
ˆ SelectedIndexChanged: Fires when selection changes
ˆ DoubleClick: Useful for item activation
Example:
2.2. BASIC INPUT CONTROLS IN DEPTH 19

1 // Single selection ListBox


2 ListBox productList = new ListBox () ;
3 productList . Location = new Point (20 , 30) ;
4 productList . Size = new Size (150 , 100) ;
5 productList . SelectionMode = SelectionMode . One ;
6 productList . Items . AddRange ( new string [] { " Laptop " , " Desktop " , "
Tablet " , " Smartphone " }) ;
7 productList . S e l e c t e d I n d e x C h a n g e d += P r o d u c t L i s t _ S e l e c t e d I n d e x C h a n g e d ;
8
9 // Multi - selection ListBox
10 ListBox featureList = new ListBox () ;
11 featureList . Location = new Point (200 , 30) ;
12 featureList . Size = new Size (150 , 100) ;
13 featureList . SelectionMode = SelectionMode . MultiExtended ; // Ctrl +
click for multiple
14 featureList . Items . AddRange ( new string [] { " WiFi " , " Bluetooth " , " NFC " ,
" GPS " , " 5 G " }) ;
15
16 // Sorted ListBox with multi - column
17 ListBox sortedList = new ListBox () ;
18 sortedList . Location = new Point (20 , 150) ;
19 sortedList . Size = new Size (200 , 80) ;
20 sortedList . Sorted = true ;
21 sortedList . ColumnWidth = 100; // For multi - column display
22 sortedList . Items . AddRange ( new string [] { " Banana " , " Apple " , " Orange " ,
" Mango " , " Grape " }) ;
23
24 // Adding / removing items dynamically
25 Button addButton = new Button () ;
26 addButton . Text = " Add Item " ;
27 addButton . Location = new Point (20 , 260) ;
28 addButton . Click += (s , e ) = > {
29 string newItem = " Item " + ( productList . Items . Count + 1) ;
30 productList . Items . Add ( newItem ) ;
31 };
32
33 Button removeButton = new Button () ;
34 removeButton . Text = " Remove Selected " ;
35 removeButton . Location = new Point (120 , 260) ;
36 removeButton . Click += (s , e ) = > {
37 if ( productList . SelectedItem != null )
38 productList . Items . Remove ( productList . SelectedItem ) ;
39 };
40
41 private void P r o d u c t L i s t _ S e l e c t e d I n d e x C h a n g e d ( object sender ,
EventArgs e )
42 {
43 ListBox list = sender as ListBox ;
44 if ( list . SelectedItem != null )
45 {
46 MessageBox . Show ( $ " Selected : { list . SelectedItem } " ) ;
47 }
48 }
49
50 // Get all selected items from multi - select list
51 Button showSelectedBtn = new Button () ;
52 showSelectedBtn . Text = " Show Selected " ;
53 showSelectedBtn . Location = new Point (220 , 260) ;
20 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

54 showSelectedBtn . Click += (s , e ) = > {


55 string selected = " " ;
56 foreach ( string item in featureList . SelectedItems )
57 {
58 selected += item + " , " ;
59 }
60 MessageBox . Show ( " Selected features : " + selected . TrimEnd ( ’ , ’ , ’ ’) )
;
61 };
Listing 2.8: Working with ListBox

2.2.8 PictureBox Control


The PictureBox displays images.
Key Properties:

ˆ Image: The displayed image


ˆ SizeMode: Controls image sizing behavior
ˆ ImageLocation: URL or path for image
ˆ WaitOnLoad: Controls asynchronous loading
ˆ BorderStyle: Optional border
SizeMode Values:

ˆ Normal: Image placed at top-left (cropped if too large)


ˆ StretchImage: Image stretched to fit control
ˆ AutoSize: Control resizes to fit image
ˆ CenterImage: Image centered (cropped if too large)
ˆ Zoom: Image scaled proportionally to fit (preserves aspect ratio)
Key Events:

ˆ Click: Useful for image-based buttons


ˆ LoadCompleted: Fires when async image loading completes
Example:
1 // PictureBox with Zoom mode ( preserves aspect ratio )
2 PictureBox photoBox = new PictureBox () ;
3 photoBox . Location = new Point (20 , 20) ;
4 photoBox . Size = new Size (200 , 150) ;
5 photoBox . SizeMode = P ic tu re Bo xS iz eM od e . Zoom ;
6 photoBox . BorderStyle = BorderStyle . FixedSingle ;
7 photoBox . Image = Image . FromFile ( @ " C :\ Images \ sample . jpg " ) ;
8
9 // PictureBox with StretchImage mode
10 PictureBox stretchBox = new PictureBox () ;
2.2. BASIC INPUT CONTROLS IN DEPTH 21

11 stretchBox . Location = new Point (240 , 20) ;


12 stretchBox . Size = new Size (200 , 150) ;
13 stretchBox . SizeMode = Pic tu re Bo xS iz eM od e . StretchImage ;
14 stretchBox . Image = Image . FromFile ( @ " C :\ Images \ logo . png " ) ;
15
16 // Load image from URL asynchronously
17 PictureBox webImage = new PictureBox () ;
18 webImage . Location = new Point (20 , 190) ;
19 webImage . Size = new Size (200 , 150) ;
20 webImage . SizeMode = Pic tu re Bo xS iz eM od e . Zoom ;
21 webImage . LoadCompleted += (s , e ) = > {
22 if (! e . Cancelled && e . Error == null )
23 {
24 MessageBox . Show ( " Image loaded successfully ! " ) ;
25 }
26 };
27 webImage . LoadAsync ( " https :// example . com / image . jpg " ) ;
28
29 // Clickable PictureBox ( acts like a button )
30 PictureBox iconButton = new PictureBox () ;
31 iconButton . Location = new Point (240 , 190) ;
32 iconButton . Size = new Size (50 , 50) ;
33 iconButton . SizeMode = Pic tu re Bo xS iz eM od e . StretchImage ;
34 iconButton . Image = Image . FromFile ( @ " C :\ Images \ icon . png " ) ;
35 iconButton . Cursor = Cursors . Hand ; // Changes cursor to hand on hover
36 iconButton . Click += (s , e ) = > {
37 MessageBox . Show ( " PictureBox clicked ! " ) ;
38 };
39
40 // Clear image
41 Button clearBtn = new Button () ;
42 clearBtn . Text = " Clear Image " ;
43 clearBtn . Location = new Point (20 , 360) ;
44 clearBtn . Click += (s , e ) = > {
45 photoBox . Image = null ;
46 };
Listing 2.9: Working with PictureBox

2.2.9 ProgressBar Control


The ProgressBar visually indicates operation progress.
Key Properties:

ˆ Minimum: Minimum value (default 0)


ˆ Maximum: Maximum value (default 100)
ˆ Value: Current position
ˆ Step: Increment for PerformStep() method
ˆ Style: Blocks, Continuous, or Marquee
ˆ MarqueeAnimationSpeed: Speed for marquee style
Style Values:
22 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

ˆ Blocks: Segmented progress display (default)


ˆ Continuous: Smooth solid bar
ˆ Marquee: Animated scrolling for indeterminate progress
Key Methods:
ˆ Increment(int value): Advances by specified amount
ˆ PerformStep(): Advances by Step property value
Example:
1 // Standard progress bar
2 ProgressBar progressBar1 = new ProgressBar () ;
3 progressBar1 . Location = new Point (20 , 30) ;
4 progressBar1 . Size = new Size (300 , 20) ;
5 progressBar1 . Minimum = 0;
6 progressBar1 . Maximum = 100;
7 progressBar1 . Value = 50; // 50% complete
8 progressBar1 . Style = ProgressBarStyle . Blocks ;
9
10 // Continuous style progress bar
11 ProgressBar continuousBar = new ProgressBar () ;
12 continuousBar . Location = new Point (20 , 60) ;
13 continuousBar . Size = new Size (300 , 20) ;
14 continuousBar . Style = ProgressBarStyle . Continuous ;
15 continuousBar . Value = 75;
16
17 // Marquee ( indeterminate ) progress bar
18 ProgressBar marqueeBar = new ProgressBar () ;
19 marqueeBar . Location = new Point (20 , 90) ;
20 marqueeBar . Size = new Size (300 , 20) ;
21 marqueeBar . Style = ProgressBarStyle . Marquee ;
22 marqueeBar . M a r q u e e A n i m a t i o n S p e e d = 50; // Speed of animation
23
24 // Simulating progress with Timer
25 Timer progressTimer = new Timer () ;
26 progressTimer . Interval = 100; // 100 ms
27 Button startBtn = new Button () ;
28 startBtn . Text = " Start Progress " ;
29 startBtn . Location = new Point (20 , 130) ;
30 startBtn . Click += (s , e ) = > {
31 progressBar1 . Value = 0;
32 progressTimer . Start () ;
33 };
34
35 progressTimer . Tick += (s , e ) = > {
36 if ( progressBar1 . Value < progressBar1 . Maximum )
37 {
38 progressBar1 . Increment (10) ; // Increase by 10
39 continuousBar . Value = progressBar1 . Value ;
40 }
41 else
42 {
43 progressTimer . Stop () ;
44 MessageBox . Show ( " Operation complete ! " ) ;
45 }
2.2. BASIC INPUT CONTROLS IN DEPTH 23

46 };
47
48 // Using Step and PerformStep
49 ProgressBar stepBar = new ProgressBar () ;
50 stepBar . Location = new Point (20 , 170) ;
51 stepBar . Size = new Size (300 , 20) ;
52 stepBar . Minimum = 0;
53 stepBar . Maximum = 10;
54 stepBar . Step = 1; // Increment by 1 each step
55
56 Button stepBtn = new Button () ;
57 stepBtn . Text = " Next Step " ;
58 stepBtn . Location = new Point (20 , 200) ;
59 stepBtn . Click += (s , e ) = > {
60 if ( stepBar . Value < stepBar . Maximum )
61 {
62 stepBar . PerformStep () ; // Advance by Step value
63 }
64 };
Listing 2.10: Working with ProgressBar

2.2.10 DataGridView Control


The DataGridView displays and edits tabular data with powerful customization.
Key Properties:

Property Description
DataSource Binds to data collections (DataTable, List, etc.)
Columns Collection of column definitions
Rows Collection of data rows
AllowUserToAddRows Enables/disables new row entry
AllowUserToDeleteRows Enables/disables row deletion
ReadOnly Prevents editing
AutoGenerateColumns Auto-creates columns from data source
SelectionMode Cell, row, or column selection behavior

Table 2.5: Key properties of the DataGridView control

Key Events:

ˆ CellClick/CellDoubleClick: Cell interaction


ˆ CellValueChanged: Data modification tracking
ˆ RowValidating: Row-level validation
Example:
1 // Basic DataGridView with manual column setup
2 DataGridView dgvProducts = new DataGridView () ;
3 dgvProducts . Location = new Point (20 , 30) ;
4 dgvProducts . Size = new Size (500 , 200) ;
5 dgvProducts . A ll ow Us er To Ad dR ow s = true ;
6 dgvProducts . A l l o w U s e r T o D e l e t e R o w s = true ;
24 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

7 dgvProducts . ReadOnly = false ;


8 dgvProducts . SelectionMode = D a t a G r i d V i e w S e l e c t i o n M o d e . FullRowSelect ;
9
10 // Define columns
11 dgvProducts . Columns . Add ( " Id " , " Product ID " ) ;
12 dgvProducts . Columns . Add ( " Name " , " Product Name " ) ;
13 dgvProducts . Columns . Add ( " Price " , " Price " ) ;
14 dgvProducts . Columns . Add ( " Stock " , " Quantity " ) ;
15
16 // Add some rows
17 dgvProducts . Rows . Add (1 , " Laptop " , 1200.50 , 10) ;
18 dgvProducts . Rows . Add (2 , " Mouse " , 25.99 , 50) ;
19 dgvProducts . Rows . Add (3 , " Keyboard " , 75.00 , 30) ;
20
21 // DataGridView bound to a list
22 List < Product > productList = new List < Product >
23 {
24 new Product { Id = 1 , Name = " Laptop " , Price = 1200.50 , Stock = 10
},
25 new Product { Id = 2 , Name = " Mouse " , Price = 25.99 , Stock = 50 } ,
26 new Product { Id = 3 , Name = " Keyboard " , Price = 75.00 , Stock = 30
}
27 };
28
29 DataGridView dgvBound = new DataGridView () ;
30 dgvBound . Location = new Point (20 , 250) ;
31 dgvBound . Size = new Size (500 , 150) ;
32 dgvBound . DataSource = productList ;
33
34 // Column customization
35 dgvBound . Columns [ " Id " ]. Width = 50;
36 dgvBound . Columns [ " Name " ]. Width = 150;
37 dgvBound . Columns [ " Price " ]. DefaultCellStyle . Format = " C2 " ; // Currency
format
38 dgvBound . Columns [ " Price " ]. DefaultCellStyle . BackColor = Color .
LightYellow ;
39 dgvBound . Columns [ " Stock " ]. DefaultCellStyle . Alignment =
D a t a G r i d V i e w C o n t e n t A l i g n m e n t . MiddleRight ;
40
41 // Event handlers
42 dgvBound . CellClick += (s , e ) = > {
43 if ( e . RowIndex >= 0 && e . ColumnIndex >= 0)
44 {
45 string value = dgvBound . Rows [ e . RowIndex ]. Cells [ e . ColumnIndex ].
Value . ToString () ;
46 MessageBox . Show ( $ " Cell value : { value } " ) ;
47 }
48 };
49

50 dgvBound . CellValueChanged += (s , e ) = > {


51 MessageBox . Show ( $ " Cell at ({ e . RowIndex } , { e . ColumnIndex }) changed
to : { dgvBound . Rows [ e . RowIndex ]. Cells [ e . ColumnIndex ]. Value } " ) ;
52 };
53
54 // Product class for data binding
55 public class Product
56 {
57 public int Id { get ; set ; }
2.3. CONTAINER CONTROLS 25

58 public string Name { get ; set ; }


59 public double Price { get ; set ; }
60 public int Stock { get ; set ; }
61 }
62
63 // Get selected row data
64 Button getSelectedBtn = new Button () ;
65 getSelectedBtn . Text = " Get Selected Product " ;
66 getSelectedBtn . Location = new Point (20 , 410) ;
67 getSelectedBtn . Click += (s , e ) = > {
68 if ( dgvBound . SelectedRows . Count > 0)
69 {
70 DataGridViewRow row = dgvBound . SelectedRows [0];
71 Product selected = row . DataBoundItem as Product ;
72 MessageBox . Show ( $ " Selected : { selected . Name } , Price : { selected .
Price : C } " ) ;
73 }
74 };
Listing 2.11: Working with DataGridView

2.3 Container Controls


Container controls organize and group other controls, improving UI structure and layout
management.

2.3.1 Panel Control


The Panel provides a generic container for grouping controls.
Key Properties:
ˆ AutoScroll: Adds scrollbars when contents exceed panel size
ˆ BorderStyle: Optional visual boundary
ˆ BackColor: Background color affecting all contained controls
Example:
1 // Panel with border
2 Panel userInfoPanel = new Panel () ;
3 userInfoPanel . Location = new Point (20 , 20) ;
4 userInfoPanel . Size = new Size (300 , 150) ;
5 userInfoPanel . BorderStyle = BorderStyle . FixedSingle ;
6 userInfoPanel . BackColor = Color . LightGray ;
7
8 // Add controls to panel
9 Label nameLabel = new Label () ;
10 nameLabel . Text = " Name : " ;
11 nameLabel . Location = new Point (10 , 10) ;
12 nameLabel . AutoSize = true ;
13

14 TextBox nameTextBox = new TextBox () ;


15 nameTextBox . Location = new Point (60 , 8) ;
16 nameTextBox . Size = new Size (200 , 20) ;
17
26 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

18 Label emailLabel = new Label () ;


19 emailLabel . Text = " Email : " ;
20 emailLabel . Location = new Point (10 , 40) ;
21 emailLabel . AutoSize = true ;
22
23 TextBox emailTextBox = new TextBox () ;
24 emailTextBox . Location = new Point (60 , 38) ;
25 emailTextBox . Size = new Size (200 , 20) ;
26
27 userInfoPanel . Controls . Add ( nameLabel ) ;
28 userInfoPanel . Controls . Add ( nameTextBox ) ;
29 userInfoPanel . Controls . Add ( emailLabel ) ;
30 userInfoPanel . Controls . Add ( emailTextBox ) ;
31
32 // Scrollable panel with many controls
33 Panel scrollPanel = new Panel () ;
34 scrollPanel . Location = new Point (20 , 180) ;
35 scrollPanel . Size = new Size (300 , 150) ;
36 scrollPanel . BorderStyle = BorderStyle . Fixed3D ;
37 scrollPanel . AutoScroll = true ;
38
39 // Add many controls to demonstrate scrolling
40 for ( int i = 0; i < 20; i ++)
41 {
42 Button btn = new Button () ;
43 btn . Text = $ " Button { i + 1} " ;
44 btn . Location = new Point (10 , 10 + ( i * 35) ) ;
45 btn . Size = new Size (250 , 30) ;
46 scrollPanel . Controls . Add ( btn ) ;
47 }
Listing 2.12: Using Panel controls

2.3.2 GroupBox Control


The GroupBox extends Panel with a titled border.
Key Properties:
ˆ Text: The title displayed on the border
ˆ FlatStyle: Visual style of the group box
Example:
1 // GroupBox for address information
2 GroupBox addressGroup = new GroupBox () ;
3 addressGroup . Text = " Address Information " ;
4 addressGroup . Location = new Point (20 , 340) ;
5 addressGroup . Size = new Size (300 , 150) ;
6 addressGroup . Font = new Font ( " Arial " , 9 , FontStyle . Bold ) ;
7
8 // Add controls to GroupBox
9 Label streetLabel = new Label () ;
10 streetLabel . Text = " Street : " ;
11 streetLabel . Location = new Point (10 , 25) ;
12 streetLabel . AutoSize = true ;
13 streetLabel . Font = new Font ( " Arial " , 8 , FontStyle . Regular ) ;
14
2.3. CONTAINER CONTROLS 27

15 TextBox streetTextBox = new TextBox () ;


16 streetTextBox . Location = new Point (60 , 23) ;
17 streetTextBox . Size = new Size (200 , 20) ;
18
19 Label cityLabel = new Label () ;
20 cityLabel . Text = " City : " ;
21 cityLabel . Location = new Point (10 , 55) ;
22 cityLabel . AutoSize = true ;
23 cityLabel . Font = new Font ( " Arial " , 8 , FontStyle . Regular ) ;
24
25 TextBox cityTextBox = new TextBox () ;
26 cityTextBox . Location = new Point (60 , 53) ;
27 cityTextBox . Size = new Size (200 , 20) ;
28
29 addressGroup . Controls . Add ( streetLabel ) ;
30 addressGroup . Controls . Add ( streetTextBox ) ;
31 addressGroup . Controls . Add ( cityLabel ) ;
32 addressGroup . Controls . Add ( cityTextBox ) ;
33

34 // GroupBox for radio button grouping ( ensures mutual exclusivity )


35 GroupBox paymentGroup = new GroupBox () ;
36 paymentGroup . Text = " Payment Method " ;
37 paymentGroup . Location = new Point (340 , 20) ;
38 paymentGroup . Size = new Size (200 , 120) ;
39

40 RadioButton cashRadio = new RadioButton () ;


41 cashRadio . Text = " Cash " ;
42 cashRadio . Location = new Point (10 , 20) ;
43 cashRadio . Checked = true ;
44
45 RadioButton cardRadio = new RadioButton () ;
46 cardRadio . Text = " Credit Card " ;
47 cardRadio . Location = new Point (10 , 45) ;
48
49 RadioButton upiRadio = new RadioButton () ;
50 upiRadio . Text = " UPI " ;
51 upiRadio . Location = new Point (10 , 70) ;
52
53 paymentGroup . Controls . Add ( cashRadio ) ;
54 paymentGroup . Controls . Add ( cardRadio ) ;
55 paymentGroup . Controls . Add ( upiRadio ) ;
Listing 2.13: Using GroupBox controls

2.3.3 TabControl
The TabControl organizes controls into multiple pages (tabs).
Key Properties:
Key Events:

ˆ SelectedIndexChanged: Fires when active tab changes


28 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

Property Description
TabPages Collection of TabPage objects
SelectedIndex Index of currently selected tab
SelectedTab Currently selected TabPage
Alignment Tab position (Top, Bottom, Left, Right)
Appearance Buttons, Normal, or FlatButtons
Multiline Allows multiple rows of tabs

Table 2.6: Key properties of the TabControl

Example:
1 TabControl tabControl = new TabControl () ;
2 tabControl . Location = new Point (20 , 20) ;
3 tabControl . Size = new Size (500 , 300) ;
4 tabControl . S e l e c t e d I n d e x C h a n g e d += T a b C o n t r o l _ S e l e c t e d I n d e x C h a n g e d ;
5

6 // Create tab pages


7 TabPage personalTab = new TabPage ( " Personal Info " ) ;
8 TabPage professionalTab = new TabPage ( " Professional " ) ;
9 TabPage settingsTab = new TabPage ( " Settings " ) ;
10
11 // Add controls to Personal tab
12 Label nameLabel = new Label () ;
13 nameLabel . Text = " Full Name : " ;
14 nameLabel . Location = new Point (20 , 20) ;
15 nameLabel . AutoSize = true ;
16
17 TextBox nameTextBox = new TextBox () ;
18 nameTextBox . Location = new Point (100 , 18) ;
19 nameTextBox . Size = new Size (200 , 20) ;
20
21 Label dobLabel = new Label () ;
22 dobLabel . Text = " Date of Birth : " ;
23 dobLabel . Location = new Point (20 , 50) ;
24 dobLabel . AutoSize = true ;
25
26 DateTimePicker dobPicker = new DateTimePicker () ;
27 dobPicker . Location = new Point (100 , 48) ;
28 dobPicker . Size = new Size (200 , 20) ;
29

30 personalTab . Controls . Add ( nameLabel ) ;


31 personalTab . Controls . Add ( nameTextBox ) ;
32 personalTab . Controls . Add ( dobLabel ) ;
33 personalTab . Controls . Add ( dobPicker ) ;
34
35 // Add controls to Professional tab
36 Label empIdLabel = new Label () ;
37 empIdLabel . Text = " Employee ID : " ;
38 empIdLabel . Location = new Point (20 , 20) ;
39 empIdLabel . AutoSize = true ;
40

41 TextBox empIdTextBox = new TextBox () ;


42 empIdTextBox . Location = new Point (100 , 18) ;
43 empIdTextBox . Size = new Size (200 , 20) ;
44
2.3. CONTAINER CONTROLS 29

45 Label deptLabel = new Label () ;


46 deptLabel . Text = " Department : " ;
47 deptLabel . Location = new Point (20 , 50) ;
48 deptLabel . AutoSize = true ;
49
50 ComboBox deptCombo = new ComboBox () ;
51 deptCombo . Location = new Point (100 , 48) ;
52 deptCombo . Size = new Size (200 , 21) ;
53 deptCombo . Items . AddRange ( new string [] { " IT " , " HR " , " Finance " , "
Marketing " }) ;
54
55 professionalTab . Controls . Add ( empIdLabel ) ;
56 professionalTab . Controls . Add ( empIdTextBox ) ;
57 professionalTab . Controls . Add ( deptLabel ) ;
58 professionalTab . Controls . Add ( deptCombo ) ;
59
60 // Add controls to Settings tab
61 CheckBox notifyCheck = new CheckBox () ;
62 notifyCheck . Text = " Enable Notifications " ;
63 notifyCheck . Location = new Point (20 , 20) ;
64 notifyCheck . Size = new Size (150 , 20) ;
65
66 CheckBox autoSaveCheck = new CheckBox () ;
67 autoSaveCheck . Text = " Auto Save " ;
68 autoSaveCheck . Location = new Point (20 , 45) ;
69 autoSaveCheck . Size = new Size (150 , 20) ;
70
71 settingsTab . Controls . Add ( notifyCheck ) ;
72 settingsTab . Controls . Add ( autoSaveCheck ) ;
73
74 // Add tabs to TabControl
75 tabControl . TabPages . Add ( personalTab ) ;
76 tabControl . TabPages . Add ( professionalTab ) ;
77 tabControl . TabPages . Add ( settingsTab ) ;
78
79 this . Controls . Add ( tabControl ) ;
80

81 private void T a b C o n t r o l _ S e l e c t e d I n d e x C h a n g e d ( object sender , EventArgs


e)
82 {
83 TabControl tc = sender as TabControl ;
84 MessageBox . Show ( $ " Switched to : { tc . SelectedTab . Text } " ) ;
85 }
Listing 2.14: Working with TabControl

2.3.4 SplitContainer
The SplitContainer creates a resizable split region between two panels.
Key Properties:

ˆ Orientation: Vertical or horizontal split


ˆ Panel1/Panel2: The two contained panels
ˆ SplitterDistance: Position of the splitter
30 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

ˆ SplitterWidth: Width of the splitter bar


ˆ FixedPanel: Panel that remains fixed size when container resizes
Example:
1 SplitContainer splitContainer = new SplitContainer () ;
2 splitContainer . Dock = DockStyle . Fill ;
3 splitContainer . Orientation = Orientation . Vertical ;
4 splitContainer . SplitterDistance = 200;
5 splitContainer . SplitterWidth = 5;
6 splitContainer . BorderStyle = BorderStyle . FixedSingle ;
7
8 // Add controls to left panel
9 ListBox fileList = new ListBox () ;
10 fileList . Dock = DockStyle . Fill ;
11 fileList . Items . AddRange ( new string [] { " Document1 . txt " , " Image . jpg " ,
" Data . xlsx " , " Report . pdf " }) ;
12 splitContainer . Panel1 . Controls . Add ( fileList ) ;
13

14 // Add controls to right panel


15 TextBox fileContent = new TextBox () ;
16 fileContent . Dock = DockStyle . Fill ;
17 fileContent . Multiline = true ;
18 fileContent . ScrollBars = ScrollBars . Both ;
19 splitContainer . Panel2 . Controls . Add ( fileContent ) ;
20
21 // Event to load content when file is selected
22 fileList . S e l e c t e d I n d e x C h a n g e d += (s , e ) = > {
23 if ( fileList . SelectedItem != null )
24 {
25 fileContent . Text = $ " Content of { fileList . SelectedItem }\ n \ nThis
is a sample preview area . " ;
26 }
27 };
28
29 this . Controls . Add ( splitContainer ) ;
30

31 // Horizontal split container example


32 SplitContainer horizontalSplit = new SplitContainer () ;
33 horizontalSplit . Location = new Point (20 , 320) ;
34 horizontalSplit . Size = new Size (500 , 150) ;
35 horizontalSplit . Orientation = Orientation . Horizontal ;
36 horizontalSplit . SplitterDistance = 60;
37 horizontalSplit . FixedPanel = FixedPanel . Panel1 ; // Top panel fixed
38
39 // Add controls to top panel
40 Label topLabel = new Label () ;
41 topLabel . Text = " Top Panel ( Fixed Height ) " ;
42 topLabel . Dock = DockStyle . Fill ;
43 topLabel . TextAlign = ContentAlignment . MiddleCenter ;
44 topLabel . BackColor = Color . LightBlue ;
45 horizontalSplit . Panel1 . Controls . Add ( topLabel ) ;
46
47 // Add controls to bottom panel
48 Label bottomLabel = new Label () ;
49 bottomLabel . Text = " Bottom Panel ( Resizable ) " ;
50 bottomLabel . Dock = DockStyle . Fill ;
51 bottomLabel . TextAlign = ContentAlignment . MiddleCenter ;
2.4. MENU AND TOOLBAR CONTROLS 31

52 bottomLabel . BackColor = Color . LightGreen ;


53 horizontalSplit . Panel2 . Controls . Add ( bottomLabel ) ;
Listing 2.15: Using SplitContainer

2.4 Menu and Toolbar Controls


2.4.1 MenuStrip
The MenuStrip creates traditional application menus.
Key Components:

ˆ ToolStripMenuItem: Individual menu items


ˆ ToolStripSeparator: Visual divider between items
MenuItem Key Properties:

ˆ Text: Display text (use & for accelerator keys, e.g., ”&File”)
ˆ ShortcutKeys: Keyboard shortcut (Ctrl+O, etc.)
ˆ Checked: Toggle state for checkable items
ˆ Enabled: Available or grayed out
Key Events:

ˆ Click: Menu item selection


Example:
1 MenuStrip menuStrip = new MenuStrip () ;
2
3 // File menu
4 Too lStrip MenuI tem fileMenu = new To olStri pMenuI tem ( " & File " ) ;
5
6 Too lStrip MenuI tem newItem = new To olStri pMenuI tem ( " & New " ) ;
7 newItem . ShortcutKeys = Keys . Control | Keys . N ;
8 newItem . Click += (s , e ) = > MessageBox . Show ( " New file created " ) ;
9

10 Too lStri pMenuI tem openItem = new To olStri pMenuI tem ( " & Open " ) ;
11 openItem . ShortcutKeys = Keys . Control | Keys . O ;
12 openItem . Click += (s , e ) = > MessageBox . Show ( " Open file dialog " ) ;
13
14 Too lStri pMenuI tem saveItem = new To olStri pMenuI tem ( " & Save " ) ;
15 saveItem . ShortcutKeys = Keys . Control | Keys . S ;
16 saveItem . Click += (s , e ) = > MessageBox . Show ( " File saved " ) ;
17
18 Too lStri pMenuI tem saveAsItem = new To olStri pMenuI tem ( " Save & As " ) ;
19
20 T oo lS tr ip Se pa ra to r separator1 = new Too lS tr ip Se pa ra to r () ;
21
22 Too lStri pMenuI tem exitItem = new To olStri pMenuI tem ( " E & xit " ) ;
23 exitItem . Click += (s , e ) = > Application . Exit () ;
24
32 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

25 fileMenu . DropDownItems . AddRange ( new ToolStripItem [] {


26 newItem , openItem , saveItem , saveAsItem , separator1 , exitItem
27 }) ;
28
29 // Edit menu
30 Too lStri pMenuI tem editMenu = new To olStri pMenuI tem ( " & Edit " ) ;
31

32 Too lStri pMenuI tem cutItem = new To olStri pMenuI tem ( " Cu & t " ) ;
33 cutItem . ShortcutKeys = Keys . Control | Keys . X ;
34
35 Too lStri pMenuI tem copyItem = new To olStri pMenuI tem ( " & Copy " ) ;
36 copyItem . ShortcutKeys = Keys . Control | Keys . C ;
37

38 Too lStri pMenuI tem pasteItem = new To olStri pMenuI tem ( " & Paste " ) ;
39 pasteItem . ShortcutKeys = Keys . Control | Keys . V ;
40
41 T oo lS tr ip Se pa ra to r separator2 = new Too lS tr ip Se pa ra to r () ;
42
43 Too lStri pMenuI tem findItem = new To olStri pMenuI tem ( " & Find " ) ;
44 findItem . ShortcutKeys = Keys . Control | Keys . F ;
45
46 editMenu . DropDownItems . AddRange ( new ToolStripItem [] {
47 cutItem , copyItem , pasteItem , separator2 , findItem
48 }) ;
49

50 // View menu with checkable items


51 Too lStri pMenuI tem viewMenu = new To olStri pMenuI tem ( " & View " ) ;
52
53 Too lStri pMenuI tem statusBarItem = new To olStri pMenuI tem ( " Status Bar " )
;
54 statusBarItem . CheckOnClick = true ;
55 statusBarItem . Checked = true ;
56
57 Too lStri pMenuI tem toolbarItem = new To olStri pMenuI tem ( " Toolbar " ) ;
58 toolbarItem . CheckOnClick = true ;
59 toolbarItem . Checked = true ;
60

61 viewMenu . DropDownItems . AddRange ( new ToolStripItem [] {


62 statusBarItem , toolbarItem
63 }) ;
64
65 // Add menus to menu strip
66 menuStrip . Items . AddRange ( new ToolStripItem [] { fileMenu , editMenu ,
viewMenu }) ;
67
68 // Add menu strip to form
69 this . MainMenuStrip = menuStrip ;
70 this . Controls . Add ( menuStrip ) ;
Listing 2.16: Creating MenuStrip

2.4.2 ToolStrip
The ToolStrip provides toolbar with quick-access buttons.
Key Features:

ˆ Can host various item types: buttons, labels, dropdowns, separators


2.4. MENU AND TOOLBAR CONTROLS 33

ˆ Supports overflow when space is limited


ˆ Can be repositioned (docked or floating)
Common Item Types:

ˆ ToolStripButton: Image/text button


ˆ ToolStripLabel: Static text or link
ˆ ToolStripDropDownButton: Button with dropdown
ˆ ToolStripSeparator: Visual divider
ˆ ToolStripComboBox: Embedded combobox
ˆ ToolStripTextBox: Embedded textbox
Example:
1 ToolStrip toolStrip = new ToolStrip () ;
2 toolStrip . Dock = DockStyle . Top ;
3
4 // Create buttons with images ( assuming images exist in resources )
5 ToolStripButton newBtn = new ToolStripButton ( " New " ) ;
6 // newBtn . Image = Properties . Resources . NewIcon ;
7 newBtn . DisplayStyle = T o o l S t r i p I t e m D i s p l a y S t y l e . ImageAndText ;
8 newBtn . Click += (s , e ) = > MessageBox . Show ( " New " ) ;
9
10 ToolStripButton openBtn = new ToolStripButton ( " Open " ) ;
11 // openBtn . Image = Properties . Resources . OpenIcon ;
12 openBtn . DisplayStyle = T o o l S t r i p I t e m D i s p l a y S t y l e . ImageAndText ;
13 openBtn . Click += (s , e ) = > MessageBox . Show ( " Open " ) ;
14
15 ToolStripButton saveBtn = new ToolStripButton ( " Save " ) ;
16 // saveBtn . Image = Properties . Resources . SaveIcon ;
17 saveBtn . DisplayStyle = T o o l S t r i p I t e m D i s p l a y S t y l e . ImageAndText ;
18 saveBtn . Click += (s , e ) = > MessageBox . Show ( " Save " ) ;
19
20 T oo lS tr ip Se pa ra to r toolSeparator1 = new Too lS tr ip Se pa ra to r () ;
21
22 ToolStripButton cutBtn = new ToolStripButton ( " Cut " ) ;
23 // cutBtn . Image = Properties . Resources . CutIcon ;
24 cutBtn . DisplayStyle = T o o l S t r i p I t e m D i s p l a y S t y l e . Image ;
25
26 ToolStripButton copyBtn = new ToolStripButton ( " Copy " ) ;
27 // copyBtn . Image = Properties . Resources . CopyIcon ;
28 copyBtn . DisplayStyle = T o o l S t r i p I t e m D i s p l a y S t y l e . Image ;
29

30 ToolStripButton pasteBtn = new ToolStripButton ( " Paste " ) ;


31 // pasteBtn . Image = Properties . Resources . PasteIcon ;
32 pasteBtn . DisplayStyle = T o o l S t r i p I t e m D i s p l a y S t y l e . Image ;
33
34 T oo lS tr ip Se pa ra to r toolSeparator2 = new Too lS tr ip Se pa ra to r () ;
35
36 // Dropdown button
37 T o o l S t r i p D r o p D o w n B u t t o n optionsBtn = new T o o l S t r i p D r o p D o w n B u t t o n ( "
Options " ) ;
34 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

38 optionsBtn . DropDownItems . Add ( " Option 1 " ) ;


39 optionsBtn . DropDownItems . Add ( " Option 2 " ) ;
40 optionsBtn . DropDownItems . Add ( new Too lS tr ip Se pa ra to r () ) ;
41 optionsBtn . DropDownItems . Add ( " Option 3 " ) ;
42
43 // ComboBox on toolbar
44 Too lStri pCombo Box fontCombo = new To olStri pCombo Box ( " Fonts " ) ;
45 fontCombo . Items . AddRange ( new object [] { " Arial " , " Times New Roman " , "
Courier New " }) ;
46 fontCombo . SelectedIndex = 0;
47
48 // TextBox on toolbar
49 ToolStripTextBox searchBox = new ToolStripTextBox ( " Search " ) ;
50 searchBox . Text = " Search ... " ;
51
52 // Add all items to toolbar
53 toolStrip . Items . AddRange ( new ToolStripItem [] {
54 newBtn , openBtn , saveBtn , toolSeparator1 ,
55 cutBtn , copyBtn , pasteBtn , toolSeparator2 ,
56 optionsBtn , fontCombo , searchBox
57 }) ;
58
59 this . Controls . Add ( toolStrip ) ;
Listing 2.17: Creating ToolStrip

2.4.3 StatusStrip
The StatusStrip displays application status information.
Common Item Types:
ˆ ToolStripStatusLabel: Text or icon display
ˆ ToolStripProgressBar: Embedded progress indicator
ˆ ToolStripDropDownButton: Status area with options
Example:
1 StatusStrip statusStrip = new StatusStrip () ;
2
3 // Status labels
4 T o o l S t r i p S t a t u s L a b e l statusLabel = new T o o l S t r i p S t a t u s L a b e l ( " Ready " ) ;
5 statusLabel . Spring = true ; // Takes available space
6 statusLabel . TextAlign = ContentAlignment . MiddleLeft ;
7
8 T o o l S t r i p S t a t u s L a b e l timeLabel = new T o o l S t r i p S t a t u s L a b e l () ;
9 timeLabel . Text = DateTime . Now . To ShortT imeStr ing () ;
10

11 T o o l S t r i p S t a t u s L a b e l capsLabel = new T o o l S t r i p S t a t u s L a b e l ( " CAPS " ) ;


12 capsLabel . BorderSides = T o o l S t r i p S t a t u s L a b e l B o r d e r S i d e s . All ;
13 capsLabel . Visible = Control . IsKeyLocked ( Keys . CapsLock ) ;
14
15 // Progress bar on status strip
16 T o o l S t r i p P r o g r e s s B a r progressBar = new T o o l S t r i p P r o g r e s s B a r () ;
17 progressBar . Size = new Size (100 , 16) ;
18 progressBar . Visible = false ;
19
2.4. MENU AND TOOLBAR CONTROLS 35

20 // Dropdown button
21 T o o l S t r i p D r o p D o w n B u t t o n statusOptions = new T o o l S t r i p D r o p D o w n B u t t o n ( "
Options " ) ;
22 statusOptions . DropDownItems . Add ( " Show Details " ) ;
23 statusOptions . DropDownItems . Add ( " Clear Status " ) ;
24 statusOptions . DropDownItems . Add ( new Too lS tr ip Se pa ra to r () ) ;
25 statusOptions . DropDownItems . Add ( " Preferences " ) ;
26
27 // Add items to status strip
28 statusStrip . Items . AddRange ( new ToolStripItem [] {
29 statusLabel ,
30 new T o o l S t r i p S t a t u s L a b e l ( " | " ) ,
31 progressBar ,
32 new T o o l S t r i p S t a t u s L a b e l ( " | " ) ,
33 timeLabel ,
34 new T o o l S t r i p S t a t u s L a b e l ( " | " ) ,
35 capsLabel ,
36 statusOptions
37 }) ;
38
39 this . Controls . Add ( statusStrip ) ;
40
41 // Update time every second
42 Timer timer = new Timer () ;
43 timer . Interval = 1000;
44 timer . Tick += (s , e ) = > {
45 timeLabel . Text = DateTime . Now . ToLongTimeString () ;
46 capsLabel . Visible = Control . IsKeyLocked ( Keys . CapsLock ) ;
47 };
48 timer . Start () ;
49

50 // Simulate long operation


51 Button processBtn = new Button () ;
52 processBtn . Text = " Start Process " ;
53 processBtn . Location = new Point (20 , 100) ;
54 processBtn . Click += (s , e ) = > {
55 statusLabel . Text = " Processing ... " ;
56 progressBar . Visible = true ;
57
58 // Simulate work
59 System . Threading . Tasks . Task . Run (() = > {
60 for ( int i = 0; i <= 100; i += 10)
61 {
62 System . Threading . Thread . Sleep (200) ;
63 this . Invoke (( MethodInvoker ) delegate {
64 progressBar . Value = i ;
65 }) ;
66 }
67

68 this . Invoke (( MethodInvoker ) delegate {


69 statusLabel . Text = " Ready " ;
70 progressBar . Visible = false ;
71 progressBar . Value = 0;
72 }) ;
73 }) ;
74 };
Listing 2.18: Creating StatusStrip
36 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

2.5 Working with Control Collections


Every container control (Form, Panel, GroupBox, etc.) has a Controls collection that
holds all child controls.

2.5.1 Common Controls Collection Operations


Adding Controls:
1 // Add single control
2 this . Controls . Add ( myButton ) ;
3
4 // Add multiple controls
5 this . Controls . AddRange ( new Control [] { button1 , textBox1 , label1 }) ;
Listing 2.19: Adding controls to a container
Removing Controls:
1 // Remove specific control
2 this . Controls . Remove ( myButton ) ;
3
4 // Remove by index
5 this . Controls . RemoveAt (0) ;
6
7 // Clear all controls
8 this . Controls . Clear () ;
Listing 2.20: Removing controls from a container
Finding Controls:
1 // Find by name ( returns array , as multiple controls could share name
)
2 Control [] found = this . Controls . Find ( " textBox1 " , true ) ;
3

4 // Iterate through all controls


5 foreach ( Control ctrl in this . Controls )
6 {
7 if ( ctrl is TextBox )
8 (( TextBox ) ctrl ) . Text = " " ;
9 }
Listing 2.21: Finding controls in a container

2.5.2 Container Hierarchy


Controls can be nested within containers. Accessing nested controls requires traversing
the hierarchy:
1 // Access a control inside a panel that ’ s on a form
2 TextBox tb = form1 . panel1 . textBox1 ;
3
4 // Dynamic access
5 Control ctrl = form1 . Controls [ " panel1 " ]. Controls [ " textBox1 " ];
6
7 // Advanced example - recursive control search
8 public Control F i n d C o n t r o l R e c u r s i v e ( Control parent , string name )
9 {
2.6. BEST PRACTICES FOR CONTROL USAGE 37

10 foreach ( Control ctrl in parent . Controls )


11 {
12 if ( ctrl . Name == name )
13 return ctrl ;
14
15 Control found = F i n d C o n t r o l R e c u r s i v e ( ctrl , name ) ;
16 if ( found != null )
17 return found ;
18 }
19 return null ;
20 }
21
22 // Usage
23 Control myControl = F i n d C o n t r o l R e c u r s i v e ( this , " textBox1 " ) ;
Listing 2.22: Accessing nested controls

2.6 Best Practices for Control Usage


2.6.1 Naming Conventions
ˆ Use descriptive, consistent prefixes (btnSubmit, txtName, lblMessage, chkAgree,
rbMale, cboCountry, lstItems)
ˆ Avoid generic names like button1, textBox2
ˆ Names should indicate purpose, not just type
2.6.2 Layout Considerations
ˆ Use Anchor and Dock properties for resize behavior
ˆ Test layouts at different resolutions
ˆ Group related controls visually and logically
ˆ Maintain consistent spacing (use Padding and Margin)
1 // Example of proper anchoring
2 Button okButton = new Button () ;
3 okButton . Text = " OK " ;
4 okButton . Location = new Point (300 , 200) ;
5 okButton . Anchor = AnchorStyles . Bottom | AnchorStyles . Right ;
6
7 // Example of docking
8 Panel toolbarPanel = new Panel () ;
9 toolbarPanel . Dock = DockStyle . Top ;
10 toolbarPanel . Height = 30;
11
12 // Consistent spacing
13 GroupBox groupBox = new GroupBox () ;
14 groupBox . Padding = new Padding (10) ; // Internal spacing
15 groupBox . Margin = new Padding (5) ; // External spacing
Listing 2.23: Layout best practices example
38 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

2.7 Student Information Management System


To consolidate the concepts learned in this chapter, we’ll build a practical Student Infor-
mation Management System.

2.7.1 Project Description


The Student Information System allows users to:

ˆ Add new students with personal and academic details


ˆ Display student list in a DataGridView
ˆ Search and filter students
ˆ View statistics
ˆ Navigate between different sections using tabs
2.7.2 Complete Code Implementation

1 using System ;
2 using System . C o l l e c t i o n s . G e n e r i c ;
3 using System . Drawing ;
4 using System . Linq ;
5 using System . Windows . Forms ;
6

7 namespace S t u d e n t I n f o S y s t e m
8 {
9 p u b l i c p a r t i a l c l a s s StudentInfoForm : Form
10 {
11 // Data s t o r a g e
12 p r i v a t e L i s t <Student> s t u d e n t s = new L i s t <Student >() ;
13 private i n t nextId = 1;
14

15 // C o n t r o l s d e c l a r a t i o n
16 p r i v a t e MenuStrip menuStrip ;
17 private ToolStrip toolStrip ;
18 private StatusStrip statusStrip ;
19 p r i v a t e TabControl t a b C o n t r o l ;
20 p r i v a t e Panel i n p u t P a n e l ;
21 p r i v a t e GroupBox personalGroupBox ;
22 p r i v a t e GroupBox academicGroupBox ;
23 p r i v a t e GroupBox searchGroupBox ;
24 p r i v a t e DataGridView dgvStudents ;
25 p r i v a t e ListBox s t a t s L i s t B o x ;
26 p r i v a t e Button btnAdd ;
27 p r i v a t e Button b t n C l e a r ;
28 p r i v a t e Button b t n D e l e t e ;
29 p r i v a t e Button b t n S e a r c h ;
30 p r i v a t e TextBox t x t S t u d e n t I d ;
2.7. STUDENT INFORMATION MANAGEMENT SYSTEM 39

31 private TextBox txtFullName ;


32 private TextBox t x t E m a i l ;
33 private TextBox txtPhone ;
34 private TextBox t x t S e a r c h ;
35 private ComboBox cboCourse ;
36 private ComboBox c b o S e m e s t e r ;
37 private ComboBox c b o S ea r c h C o u r s e ;
38 private RadioButton rbMale ;
39 private RadioButton rbFemale ;
40 private RadioButton rbOther ;
41 private RadioButton r b S e a r c h A l l ;
42 private RadioButton rbSearchByCourse ;
43 private DateTimePicker dtpBirthDate ;
44 private CheckBox c h k H o s t e l ;
45 private CheckBox c h k S c h o l a r s h i p ;
46 private NumericUpDown nudAttendance ;
47 private NumericUpDown nudMarks ;
48 private L ab el l b l S t a t u s ;
49

50 p u b l i c StudentInfoForm ( )
51 {
52 InitializeComponent () ;
53 SetupForm ( ) ;
54 LoadSampleData ( ) ;
55 UpdateStudentGrid ( ) ;
56 }
57

58 private void InitializeComponent ( )


59 {
60 t h i s . Text = ” Student I n f o r m a t i o n Management System ” ;
61 t h i s . S i z e = new S i z e ( 9 0 0 , 7 0 0 ) ;
62 t h i s . S t a r t P o s i t i o n = FormStartPosition . CenterScreen ;
63 t h i s . BackColor = C o l o r . White ;
64 }
65

66 p r i v a t e v o i d SetupForm ( )
67 {
68 // C r e a t e Menu S t r i p
69 CreateMenuStrip ( ) ;
70

71 // C r e a t e Tool S t r i p
72 CreateToolStrip () ;
73

74 // C r e a t e S t a t u s S t r i p
75 CreateStatusStrip () ;
76

77 // C r e a t e Tab C o n t r o l
78 CreateTabControl ( ) ;
79

80 // C r e a t e Input Panel and C o n t r o l s


81 CreateInputPanel ( ) ;
40 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

82

83 // C r e a t e DataGridView
84 CreateDataGridView ( ) ;
85

86 // C r e a t e S t a t i s t i c s Panel
87 CreateStatisticsPanel () ;
88

89 // Add c o n t r o l s t o form
90 t h i s . C o n t r o l s . Add( menuStrip ) ;
91 t h i s . C o n t r o l s . Add( t o o l S t r i p ) ;
92 t h i s . C o n t r o l s . Add( t a b C o n t r o l ) ;
93 t h i s . C o n t r o l s . Add( s t a t u s S t r i p ) ;
94

95 // S e t main menu f o r form


96 t h i s . MainMenuStrip = menuStrip ;
97 }
98

99 p r i v a t e v o i d CreateMenuStrip ( )
100 {
101 menuStrip = new MenuStrip ( ) ;
102

103 // F i l e Menu
104 ToolStripMenuItem f i l e M e n u = new ToolStripMenuItem ( ”&F i l e ” ) ;
105

106 ToolStripMenuItem newItem = new ToolStripMenuItem ( ”&New


Student ” ) ;
107 newItem . ShortcutKeys = Keys . C o n t r o l | Keys .N;
108 newItem . C l i c k += ( s , e ) => C l e a r I n p u t F i e l d s ( ) ;
109

110 ToolStripMenuItem e x i t I t e m = new ToolStripMenuItem ( ”E&x i t ” ) ;


111 e x i t I t e m . ShortcutKeys = Keys . Alt | Keys . F4 ;
112 e x i t I t e m . C l i c k += ( s , e ) => A p p l i c a t i o n . E x i t ( ) ;
113

114 f i l e M e n u . DropDownItems . AddRange ( new T o o l S t r i p I t e m [ ] {


newItem , new T o o l S t r i p S e p a r a t o r ( ) , e x i t I t e m } ) ;
115

116 // View Menu


117 ToolStripMenuItem viewMenu = new ToolStripMenuItem ( ”&View” ) ;
118

119 ToolStripMenuItem showStatsItem = new ToolStripMenuItem ( ”


Show S t a t i s t i c s ” ) ;
120 showStatsItem . CheckOnClick = t r u e ;
121 showStatsItem . Checked = t r u e ;
122 showStatsItem . C l i c k += ( s , e ) => s t a t s L i s t B o x . V i s i b l e =
showStatsItem . Checked ;
123

124 viewMenu . DropDownItems . Add( showStatsItem ) ;


125

126 // Help Menu


127 ToolStripMenuItem helpMenu = new ToolStripMenuItem ( ”&Help ” ) ;
128
2.7. STUDENT INFORMATION MANAGEMENT SYSTEM 41

129 ToolStripMenuItem aboutItem = new ToolStripMenuItem ( ”&About”


);
130 aboutItem . C l i c k += ( s , e ) => MessageBox . Show ( ” Student
I n f o r m a t i o n System \ n V e r s i o n 1 . 0 \ n\ nDeveloped f o r Windows Forms
T u t o r i a l ” , ”About” ) ;
131

132 helpMenu . DropDownItems . Add( aboutItem ) ;


133

134 menuStrip . Items . AddRange ( new T o o l S t r i p I t e m [ ] { f i l e M e n u ,


viewMenu , helpMenu } ) ;
135 }
136

137 private void CreateToolStrip ( )


138 {
139 t o o l S t r i p = new T o o l S t r i p ( ) ;
140

141 T o o l S t r i p B u t t o n btnNew = new T o o l S t r i p B u t t o n ( ”New” ) ;


142 btnNew . C l i c k += ( s , e ) => C l e a r I n p u t F i e l d s ( ) ;
143

144 T o o l S t r i p B u t t o n btnSave = new T o o l S t r i p B u t t o n ( ” Save ” ) ;


145 btnSave . C l i c k += ( s , e ) => btnAdd . P e r f o r m C l i c k ( ) ;
146

147 T o o l S t r i p B u t t o n b t n D e l e t e = new T o o l S t r i p B u t t o n ( ” D e l e t e ” ) ;
148 b t n D e l e t e . C l i c k += ( s , e ) => b t n D e l e t e . P e r f o r m C l i c k ( ) ;
149

150 T o o l S t r i p B u t t o n b t n R e f r e s h = new T o o l S t r i p B u t t o n ( ” R e f r e s h ” ) ;
151 b t n R e f r e s h . C l i c k += ( s , e ) => UpdateStudentGrid ( ) ;
152

153 T o o l S t r i p S e p a r a t o r s e p = new T o o l S t r i p S e p a r a t o r ( ) ;
154

155 T o o l S t r i p L a b e l l b l I n f o = new T o o l S t r i p L a b e l ( ” Student


Management System ” ) ;
156

157 t o o l S t r i p . Items . AddRange ( new T o o l S t r i p I t e m [ ] {


158 btnNew , btnSave , b t n D e l e t e , b t n R e f r e s h , sep , l b l I n f o
159 }) ;
160 }
161

162 private void CreateStatusStrip ()


163 {
164 s t a t u s S t r i p = new S t a t u s S t r i p ( ) ;
165

166 l b l S t a t u s = new T o o l S t r i p S t a t u s L a b e l ( ”Ready” ) ;


167 l b l S t a t u s . Spring = true ;
168 l b l S t a t u s . TextAlign = ContentAlignment . M i d d l e L e f t ;
169

170 T o o l S t r i p S t a t u s L a b e l l b l D a t e = new T o o l S t r i p S t a t u s L a b e l ( ) ;
171 l b l D a t e . Text = DateTime . Now . T o S h o r t D a t e S t r i n g ( ) ;
172

173 T o o l S t r i p S t a t u s L a b e l l b l T i m e = new T o o l S t r i p S t a t u s L a b e l ( ) ;
174 l b l T i m e . Text = DateTime . Now . ToShortTimeString ( ) ;
42 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

175

176 // Update time e v e r y s e c o n d


177 Timer t i m e r = new Timer ( ) ;
178 timer . I n t e r v a l = 1000;
179 t i m e r . Tick += ( s , e ) => l b l T i m e . Text = DateTime . Now .
ToLongTimeString ( ) ;
180 timer . Start () ;
181

182 s t a t u s S t r i p . Items . AddRange ( new T o o l S t r i p I t e m [ ] { l b l S t a t u s ,


lblDate , lblTime }) ;
183 }
184

185 p r i v a t e v o i d CreateTabControl ( )
186 {
187 t a b C o n t r o l = new TabControl ( ) ;
188 t a b C o n t r o l . L o c a t i o n = new P oi nt ( 1 0 , 6 0 ) ;
189 t a b C o n t r o l . S i z e = new S i z e ( 8 6 0 , 5 5 0 ) ;
190 t a b C o n t r o l . Anchor = A n c h o r S t y l e s . Top | A n c h o r S t y l e s . Bottom |
A n c h o r S t y l e s . L e f t | A n c h o r S t y l e s . Right ;
191

192 // C r e a t e t a b s
193 TabPage inputTab = new TabPage ( ” Student R e g i s t r a t i o n ” ) ;
194 TabPage viewTab = new TabPage ( ”View S t u d e n t s ” ) ;
195 TabPage searchTab = new TabPage ( ” S e a r c h & Reports ” ) ;
196

197 t a b C o n t r o l . TabPages . Add( inputTab ) ;


198 t a b C o n t r o l . TabPages . Add( viewTab ) ;
199 t a b C o n t r o l . TabPages . Add( searchTab ) ;
200

201 // Setup each tab


202 SetupInputTab ( inputTab ) ;
203 SetupViewTab ( viewTab ) ;
204 SetupSearchTab ( searchTab ) ;
205 }
206

207 p r i v a t e v o i d SetupInputTab ( TabPage tab )


208 {
209 // P e r s o n a l I n f o r m a t i o n GroupBox
210 personalGroupBox = new GroupBox ( ) ;
211 personalGroupBox . Text = ” P e r s o n a l I n f o r m a t i o n ” ;
212 personalGroupBox . L o c a t i o n = new Po in t ( 1 0 , 1 0 ) ;
213 personalGroupBox . S i z e = new S i z e ( 4 0 0 , 2 0 0 ) ;
214 personalGroupBox . Font = new Font ( ” A r i a l ” , 9 , F o n t S t y l e . Bold )
;
215

216 // Student ID ( auto =g e n e r a t e d , read =o n l y )


217 L ab el l b l I d = new La be l ( ) ;
218 l b l I d . Text = ” Student ID : ” ;
219 l b l I d . L o c a t i o n = new Po in t ( 1 0 , 2 5 ) ;
220 l b l I d . S i z e = new S i z e ( 1 0 0 , 2 0 ) ;
221 l b l I d . Font = new Font ( ” A r i a l ” , 8 , F o n t S t y l e . Reg ular ) ;
2.7. STUDENT INFORMATION MANAGEMENT SYSTEM 43

222

223 t x t S t u d e n t I d = new TextBox ( ) ;


224 t x t S t u d e n t I d . L o c a t i o n = new Po i nt ( 1 2 0 , 2 3 ) ;
225 t x t S t u d e n t I d . S i z e = new S i z e ( 1 5 0 , 2 0 ) ;
226 t x t S t u d e n t I d . ReadOnly = t r u e ;
227 t x t S t u d e n t I d . BackColor = C o l o r . LightGray ;
228 t x t S t u d e n t I d . Text = ”Auto= g e n e r a t e d ” ;
229

230 // F u l l Name
231 L ab el lblName = new La be l ( ) ;
232 lblName . Text = ” F u l l Name : ” ;
233 lblName . L o c a t i o n = new Po i nt ( 1 0 , 5 0 ) ;
234 lblName . S i z e = new S i z e ( 1 0 0 , 2 0 ) ;
235 lblName . Font = new Font ( ” A r i a l ” , 8 , F o n t S t y l e . Reg ular ) ;
236

237 txtFullName = new TextBox ( ) ;


238 txtFullName . L o c a t i o n = new Po in t ( 1 2 0 , 4 8 ) ;
239 txtFullName . S i z e = new S i z e ( 2 5 0 , 2 0 ) ;
240

241 // B i r t h Date
242 L ab el lblDob = new La be l ( ) ;
243 lblDob . Text = ” B i r t h Date : ” ;
244 lblDob . L o c a t i o n = new P oi nt ( 1 0 , 7 5 ) ;
245 lblDob . S i z e = new S i z e ( 1 0 0 , 2 0 ) ;
246 lblDob . Font = new Font ( ” A r i a l ” , 8 , F o n t S t y l e . Reg ula r ) ;
247

248 dtpBirthDate = new DateTimePicker ( ) ;


249 dtpBirthDate . L o c a t i o n = new P oi nt ( 1 2 0 , 7 3 ) ;
250 dtpBirthDate . S i z e = new S i z e ( 1 5 0 , 2 0 ) ;
251 dtpBirthDate . Format = DateTimePickerFormat . S h o r t ;
252 dtpBirthDate . MaxDate = DateTime . Today . AddYears ( = 15) ; //
Minimum 15 y e a r s o l d
253

254 // Gender
255 L ab el l b l G e n d e r = new La b el ( ) ;
256 l b l G e n d e r . Text = ” Gender : ” ;
257 l b l G e n d e r . L o c a t i o n = new P oi nt ( 1 0 , 1 0 0 ) ;
258 l b l G e n d e r . S i z e = new S i z e ( 1 0 0 , 2 0 ) ;
259 l b l G e n d e r . Font = new Font ( ” A r i a l ” , 8 , F o n t S t y l e . Re gula r ) ;
260

261 rbMale = new RadioButton ( ) ;


262 rbMale . Text = ” Male ” ;
263 rbMale . L o c a t i o n = new Po in t ( 1 2 0 , 9 8 ) ;
264 rbMale . S i z e = new S i z e ( 6 0 , 2 0 ) ;
265 rbMale . Checked = t r u e ;
266

267 rbFemale = new RadioButton ( ) ;


268 rbFemale . Text = ” Female ” ;
269 rbFemale . L o c a t i o n = new Po in t ( 1 9 0 , 9 8 ) ;
270 rbFemale . S i z e = new S i z e ( 7 0 , 2 0 ) ;
271
44 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

272 rbOther = new RadioButton ( ) ;


273 rbOther . Text = ” Other ” ;
274 rbOther . L o c a t i o n = new P oi nt ( 2 7 0 , 9 8 ) ;
275 rbOther . S i z e = new S i z e ( 6 0 , 2 0 ) ;
276

277 // Email
278 L ab el l b l E m a i l = new La be l ( ) ;
279 l b l E m a i l . Text = ” Email : ” ;
280 l b l E m a i l . L o c a t i o n = new P oi nt ( 1 0 , 1 2 5 ) ;
281 l b l E m a i l . S i z e = new S i z e ( 1 0 0 , 2 0 ) ;
282 l b l E m a i l . Font = new Font ( ” A r i a l ” , 8 , F o n t S t y l e . Reg ula r ) ;
283

284 t x t E m a i l = new TextBox ( ) ;


285 t x t E m a i l . L o c a t i o n = new Po in t ( 1 2 0 , 1 2 3 ) ;
286 t x t E m a i l . S i z e = new S i z e ( 2 5 0 , 2 0 ) ;
287

288 // Phone
289 L ab el l b l P h o n e = new L ab el ( ) ;
290 l b l P h o n e . Text = ”Phone : ” ;
291 l b l P h o n e . L o c a t i o n = new P o in t ( 1 0 , 1 5 0 ) ;
292 l b l P h o n e . S i z e = new S i z e ( 1 0 0 , 2 0 ) ;
293 l b l P h o n e . Font = new Font ( ” A r i a l ” , 8 , F o n t S t y l e . Re gul ar ) ;
294

295 txtPhone = new TextBox ( ) ;


296 txtPhone . L o c a t i o n = new P oi nt ( 1 2 0 , 1 4 8 ) ;
297 txtPhone . S i z e = new S i z e ( 1 5 0 , 2 0 ) ;
298 txtPhone . MaxLength = 1 0 ;
299

300 // Add c o n t r o l s t o p e r s o n a l group


301 personalGroupBox . C o n t r o l s . AddRange ( new C o n t r o l [ ] {
302 lblId , txtStudentId ,
303 lblName , txtFullName ,
304 lblDob , dtpBirthDate ,
305 l b l G e n d e r , rbMale , rbFemale , rbOther ,
306 l b l E m a i l , txtEmail ,
307 lblPhone , txtPhone
308 }) ;
309

310 // Academic I n f o r m a t i o n GroupBox


311 academicGroupBox = new GroupBox ( ) ;
312 academicGroupBox . Text = ” Academic I n f o r m a t i o n ” ;
313 academicGroupBox . L o c a t i o n = new P oi nt ( 1 0 , 2 2 0 ) ;
314 academicGroupBox . S i z e = new S i z e ( 4 0 0 , 2 0 0 ) ;
315 academicGroupBox . Font = new Font ( ” A r i a l ” , 9 , F o n t S t y l e . Bold )
;
316

317 // Course
318 L ab el l b l C o u r s e = new L ab el ( ) ;
319 l b l C o u r s e . Text = ” Course : ” ;
320 l b l C o u r s e . L o c a t i o n = new P oi nt ( 1 0 , 2 5 ) ;
321 l b l C o u r s e . S i z e = new S i z e ( 1 0 0 , 2 0 ) ;
2.7. STUDENT INFORMATION MANAGEMENT SYSTEM 45

322 l b l C o u r s e . Font = new Font ( ” A r i a l ” , 8 , F o n t S t y l e . Re gul ar ) ;


323

324 cboCourse = new ComboBox ( ) ;


325 cboCourse . L o c a t i o n = new Po in t ( 1 2 0 , 2 3 ) ;
326 cboCourse . S i z e = new S i z e ( 1 5 0 , 2 1 ) ;
327 cboCourse . DropDownStyle = ComboBoxStyle . DropDownList ;
328 cboCourse . Items . AddRange ( new s t r i n g [ ] { ”Computer S c i e n c e ” ,
” I n f o r m a t i o n Technology ” , ” B u s i n e s s A d m i n i s t r a t i o n ” , ” E n g i n e e r i n g
” , ” Mathematics ” } ) ;
329

330 // S e m e s t e r
331 L ab el l b l S e m e s t e r = new L ab el ( ) ;
332 l b l S e m e s t e r . Text = ” S e m e s t e r : ” ;
333 l b l S e m e s t e r . L o c a t i o n = new Po in t ( 1 0 , 5 0 ) ;
334 l b l S e m e s t e r . S i z e = new S i z e ( 1 0 0 , 2 0 ) ;
335 l b l S e m e s t e r . Font = new Font ( ” A r i a l ” , 8 , F o n t S t y l e . R egul ar ) ;
336

337 c b o S e m e s t e r = new ComboBox ( ) ;


338 c b o S e m e s t e r . L o c a t i o n = new Po in t ( 1 2 0 , 4 8 ) ;
339 c b o S e m e s t e r . S i z e = new S i z e ( 8 0 , 2 1 ) ;
340 c b o S e m e s t e r . DropDownStyle = ComboBoxStyle . DropDownList ;
341 c b o S e m e s t e r . Items . AddRange ( new s t r i n g [ ] { ” 1 ” , ” 2 ” , ” 3 ” , ” 4 ”
, ”5” , ” 6 ” , ” 7 ” , ” 8 ” } ) ;
342

343 // Attendance P e r c e n t a g e
344 L ab el l b l A t t e n d a n c e = new La be l ( ) ;
345 l b l A t t e n d a n c e . Text = ” Attendance %:” ;
346 l b l A t t e n d a n c e . L o c a t i o n = new Po in t ( 1 0 , 7 5 ) ;
347 l b l A t t e n d a n c e . S i z e = new S i z e ( 1 0 0 , 2 0 ) ;
348 l b l A t t e n d a n c e . Font = new Font ( ” A r i a l ” , 8 , F o n t S t y l e . Regu lar )
;
349

350 nudAttendance = new NumericUpDown ( ) ;


351 nudAttendance . L o c a t i o n = new P oi nt ( 1 2 0 , 7 3 ) ;
352 nudAttendance . S i z e = new S i z e ( 6 0 , 2 0 ) ;
353 nudAttendance . Minimum = 0 ;
354 nudAttendance . Maximum = 1 0 0 ;
355 nudAttendance . Value = 7 5 ;
356

357 // Marks P e r c e n t a g e
358 L ab el l b l M a r k s = new La be l ( ) ;
359 l b l M a r k s . Text = ”Marks %:” ;
360 l b l M a r k s . L o c a t i o n = new P oi nt ( 1 0 , 1 0 0 ) ;
361 l b l M a r k s . S i z e = new S i z e ( 1 0 0 , 2 0 ) ;
362 l b l M a r k s . Font = new Font ( ” A r i a l ” , 8 , F o n t S t y l e . Reg ula r ) ;
363

364 nudMarks = new NumericUpDown ( ) ;


365 nudMarks . L o c a t i o n = new P o in t ( 1 2 0 , 9 8 ) ;
366 nudMarks . S i z e = new S i z e ( 6 0 , 2 0 ) ;
367 nudMarks . Minimum = 0 ;
368 nudMarks . Maximum = 1 0 0 ;
46 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

369 nudMarks . Value = 6 0 ;


370

371 // Options
372 c h k H o s t e l = new CheckBox ( ) ;
373 c h k H o s t e l . Text = ” H o s t e l Accommodation ” ;
374 c h k H o s t e l . L o c a t i o n = new Po in t ( 1 2 0 , 1 2 5 ) ;
375 c h k H o s t e l . S i z e = new S i z e ( 1 5 0 , 2 0 ) ;
376

377 c h k S c h o l a r s h i p = new CheckBox ( ) ;


378 c h k S c h o l a r s h i p . Text = ” S c h o l a r s h i p ” ;
379 c h k S c h o l a r s h i p . L o c a t i o n = new Po in t ( 1 2 0 , 1 5 0 ) ;
380 c h k S c h o l a r s h i p . S i z e = new S i z e ( 1 5 0 , 2 0 ) ;
381

382 // Add c o n t r o l s t o academic group


383 academicGroupBox . C o n t r o l s . AddRange ( new C o n t r o l [ ] {
384 l b l C o u r s e , cboCourse ,
385 l b l S e m e s t e r , cboSemester ,
386 l b l A t t e n d a n c e , nudAttendance ,
387 lblMarks , nudMarks ,
388 chkHostel , chkScholarship
389 }) ;
390

391 // Buttons Panel


392 Panel b u tt o n Pa n e l = new Panel ( ) ;
393 b u t to n P an e l . L o c a t i o n = new Po in t ( 1 0 , 4 3 0 ) ;
394 b u t to n P an e l . S i z e = new S i z e ( 4 0 0 , 5 0 ) ;
395

396 btnAdd = new Button ( ) ;


397 btnAdd . Text = ”Add Student ” ;
398 btnAdd . L o c a t i o n = new Po in t ( 5 0 , 1 0 ) ;
399 btnAdd . S i z e = new S i z e ( 1 0 0 , 3 0 ) ;
400 btnAdd . BackColor = C o l o r . LightGreen ;
401 btnAdd . C l i c k += BtnAdd Click ;
402

403 b t n C l e a r = new Button ( ) ;


404 b t n C l e a r . Text = ” C l e a r F i e l d s ” ;
405 b t n C l e a r . L o c a t i o n = new Po in t ( 1 6 0 , 1 0 ) ;
406 b t n C l e a r . S i z e = new S i z e ( 1 0 0 , 3 0 ) ;
407 b t n C l e a r . C l i c k += ( s , e ) => C l e a r I n p u t F i e l d s ( ) ;
408

409 b t n D e l e t e = new Button ( ) ;


410 b t n D e l e t e . Text = ” D e l e t e Student ” ;
411 b t n D e l e t e . L o c a t i o n = new Po i nt ( 2 7 0 , 1 0 ) ;
412 b t n D e l e t e . S i z e = new S i z e ( 1 0 0 , 3 0 ) ;
413 b t n D e l e t e . BackColor = C o l o r . L i g h t C o r a l ;
414 b t n D e l e t e . C l i c k += B t n D e l e t e C l i c k ;
415

416 b u t to n P an e l . C o n t r o l s . AddRange ( new C o n t r o l [ ] { btnAdd ,


btnClear , b t n D e l e t e } ) ;
417

418 // Add a l l t o tab


2.7. STUDENT INFORMATION MANAGEMENT SYSTEM 47

419 tab . C o n t r o l s . Add( personalGroupBox ) ;


420 tab . C o n t r o l s . Add( academicGroupBox ) ;
421 tab . C o n t r o l s . Add( bu t t o nP a ne l ) ;
422 }
423

424 p r i v a t e v o i d SetupViewTab ( TabPage tab )


425 {
426 // S e a r c h p a n e l
427 Panel s e a r c h P a n e l = new Panel ( ) ;
428 s e a r c h P a n e l . L o c a t i o n = new Po i nt ( 1 0 , 1 0 ) ;
429 s e a r c h P a n e l . S i z e = new S i z e ( 8 2 0 , 5 0 ) ;
430 searchPanel . BorderStyle = BorderStyle . FixedSingle ;
431

432 L ab el l b l S e a r c h = new La be l ( ) ;
433 l b l S e a r c h . Text = ” S e a r c h : ” ;
434 l b l S e a r c h . L o c a t i o n = new Po i nt ( 1 0 , 1 5 ) ;
435 l b l S e a r c h . AutoSize = t r u e ;
436

437 t x t S e a r c h = new TextBox ( ) ;


438 t x t S e a r c h . L o c a t i o n = new Po in t ( 7 0 , 1 3 ) ;
439 t x t S e a r c h . S i z e = new S i z e ( 2 0 0 , 2 0 ) ;
440 t x t S e a r c h . TextChanged += TxtSearch TextChanged ;
441

442 b t n S e a r c h = new Button ( ) ;


443 b t n S e a r c h . Text = ” S e a r c h ” ;
444 b t n S e a r c h . L o c a t i o n = new P oi nt ( 2 8 0 , 1 2 ) ;
445 b t n S e a r c h . S i z e = new S i z e ( 7 5 , 2 3 ) ;
446 b t n S e a r c h . C l i c k += ( s , e ) => F i l t e r S t u d e n t s ( ) ;
447

448 Button b tnReset = new Button ( ) ;


449 btnReset . Text = ” Reset ” ;
450 btnReset . L o c a t i o n = new Po in t ( 3 6 0 , 1 2 ) ;
451 btnReset . S i z e = new S i z e ( 7 5 , 2 3 ) ;
452 btnReset . C l i c k += ( s , e ) => {
453 txtSearch . Clear () ;
454 UpdateStudentGrid ( ) ;
455 };
456

457 s e a r c h P a n e l . C o n t r o l s . AddRange ( new C o n t r o l [ ] { l b l S e a r c h ,


t x t S e a r c h , btnSearch , btnRe set } ) ;
458

459 // DataGridView
460 dgvStudents = new DataGridView ( ) ;
461 dgvStudents . L o c a t i o n = new P o in t ( 1 0 , 7 0 ) ;
462 dgvStudents . S i z e = new S i z e ( 8 2 0 , 4 0 0 ) ;
463 dgvStudents . Anchor = A n c h o r S t y l e s . Top | A n c h o r S t y l e s . Bottom
| A n c h o r S t y l e s . L e f t | A n c h o r S t y l e s . Right ;
464 dgvStudents . AllowUserToAddRows = f a l s e ;
465 dgvStudents . AllowUserToDeleteRows = f a l s e ;
466 dgvStudents . ReadOnly = t r u e ;
467 dgvStudents . S e l e c t i o n M o d e = DataGridViewSelectionMode .
48 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

FullRowSelect ;
468 dgvStudents . M u l t i S e l e c t = f a l s e ;
469 dgvStudents . AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode . F i l l ;
470 dgvStudents . RowHeaders Visible = f a l s e ;
471

472 // Add s e l e c t i o n changed e v e n t


473 dgvStudents . S e l e c t i o n C h a n g e d += D g v S t u d e n t s S e l e c t i o n C h a n g e d
;
474

475 tab . C o n t r o l s . Add( s e a r c h P a n e l ) ;


476 tab . C o n t r o l s . Add( dgvStudents ) ;
477 }
478

479 p r i v a t e v o i d SetupSearchTab ( TabPage tab )


480 {
481 // S e a r c h by c o u r s e group
482 searchGroupBox = new GroupBox ( ) ;
483 searchGroupBox . Text = ” S e a r c h F i l t e r s ” ;
484 searchGroupBox . L o c a t i o n = new Po in t ( 1 0 , 1 0 ) ;
485 searchGroupBox . S i z e = new S i z e ( 3 0 0 , 1 5 0 ) ;
486

487 r b S e a r c h A l l = new RadioButton ( ) ;


488 r b S e a r c h A l l . Text = ”Show A l l S t u d e n t s ” ;
489 r b S e a r c h A l l . L o c a t i o n = new P oi nt ( 1 0 , 2 0 ) ;
490 r b S e a r c h A l l . S i z e = new S i z e ( 1 5 0 , 2 0 ) ;
491 r b S e a r c h A l l . Checked = t r u e ;
492 r b S e a r c h A l l . CheckedChanged += F i l t e r R a d i o C h e c k e d C h a n g e d ;
493

494 rbSearchByCourse = new RadioButton ( ) ;


495 rbSearchByCourse . Text = ” F i l t e r by Course : ” ;
496 rbSearchByCourse . L o c a t i o n = new Po in t ( 1 0 , 4 5 ) ;
497 rbSearchByCourse . S i z e = new S i z e ( 1 2 0 , 2 0 ) ;
498

499 c b o S e a r c h C o u r s e = new ComboBox ( ) ;


500 c b o S e a r c h C o u r s e . L o c a t i o n = new Po in t ( 1 3 0 , 4 3 ) ;
501 c b o S e a r c h C o u r s e . S i z e = new S i z e ( 1 5 0 , 2 1 ) ;
502 c b o S e a r c h C o u r s e . DropDownStyle = ComboBoxStyle . DropDownList ;
503 c b o S e a r c h C o u r s e . Items . AddRange ( new s t r i n g [ ] { ”Computer
S c i e n c e ” , ” I n f o r m a t i o n Technology ” , ” B u s i n e s s A d m i n i s t r a t i o n ” , ”
E n g i n e e r i n g ” , ” Mathematics ” } ) ;
504 c b o S e a r c h C o u r s e . S e l e c t e d I n d e x C h a n g e d +=
FilterCombo SelectedIndexChanged ;
505

506 Button btnShowStats = new Button ( ) ;


507 btnShowStats . Text = ”Show S t a t i s t i c s ” ;
508 btnShowStats . L o c a t i o n = new Po in t ( 1 0 , 8 0 ) ;
509 btnShowStats . S i z e = new S i z e ( 1 2 0 , 3 0 ) ;
510 btnShowStats . C l i c k += B t n S h o w S t a t s C l i c k ;
511

512 Button btnExport = new Button ( ) ;


2.7. STUDENT INFORMATION MANAGEMENT SYSTEM 49

513 btnExport . Text = ” Export t o CSV” ;


514 btnExport . L o c a t i o n = new P oi nt ( 1 4 0 , 8 0 ) ;
515 btnExport . S i z e = new S i z e ( 1 2 0 , 3 0 ) ;
516 btnExport . C l i c k += B t n E x p o r t C l i c k ;
517

518 searchGroupBox . C o n t r o l s . AddRange ( new C o n t r o l [ ] {


519 r b S e a r c h A l l , rbSearchByCourse , cboSearchCourse ,
520 btnShowStats , btnExport
521 }) ;
522

523 // S t a t i s t i c s ListBox
524 GroupBox s t a t s G r o u p = new GroupBox ( ) ;
525 s t a t s G r o u p . Text = ” S t a t i s t i c s ” ;
526 s t a t s G r o u p . L o c a t i o n = new Po in t ( 3 2 0 , 1 0 ) ;
527 s t a t s G r o u p . S i z e = new S i z e ( 3 0 0 , 3 0 0 ) ;
528

529 s t a t s L i s t B o x = new ListBox ( ) ;


530 s t a t s L i s t B o x . L o c a t i o n = new P oi nt ( 1 0 , 2 0 ) ;
531 s t a t s L i s t B o x . S i z e = new S i z e ( 2 8 0 , 2 6 0 ) ;
532

533 s t a t s G r o u p . C o n t r o l s . Add( s t a t s L i s t B o x ) ;
534

535 tab . C o n t r o l s . Add( searchGroupBox ) ;


536 tab . C o n t r o l s . Add( s t a t s G r o u p ) ;
537 }
538

539 p r i v a t e v o i d CreateDataGridView ( )
540 {
541 // DataGridView a l r e a d y c r e a t e d i n SetupViewTab
542 }
543

544 private void C r e a t e S t a t i s t i c s P a n e l ( )


545 {
546 // S t a t i s t i c s p a n e l c r e a t e d i n SetupSearchTab
547 }
548

549 p r i v a t e v o i d LoadSampleData ( )
550 {
551 // Add some sample s t u d e n t s
552 s t u d e n t s . Add( new Student
553 {
554 Id = n e x t I d ++,
555 FullName = ” John Doe” ,
556 BirthDate = new DateTime ( 2 0 0 0 , 5 , 1 5 ) ,
557 Gender = ” Male ” ,
558 Email = ” john . doe@email . com” ,
559 Phone = ” 1234567890 ” ,
560 Course = ”Computer S c i e n c e ” ,
561 Semester = 3 ,
562 Attendance = 8 5 ,
563 Marks = 7 8 ,
50 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

564 Hostel = true ,


565 Scholarship = f a l s e
566 }) ;
567

568 s t u d e n t s . Add( new Student


569 {
570 Id = n e x t I d ++,
571 FullName = ” Jane Smith ” ,
572 BirthDate = new DateTime ( 2 0 0 1 , 8 , 2 2 ) ,
573 Gender = ” Female ” ,
574 Email = ” j a n e . smith@email . com” ,
575 Phone = ” 9876543210 ” ,
576 Course = ” B u s i n e s s A d m i n i s t r a t i o n ” ,
577 Semester = 2 ,
578 Attendance = 9 2 ,
579 Marks = 8 8 ,
580 Hostel = false ,
581 Scholarship = true
582 }) ;
583

584 s t u d e n t s . Add( new Student


585 {
586 Id = n e x t I d ++,
587 FullName = ”Bob Johnson ” ,
588 BirthDate = new DateTime ( 2 0 0 0 , 1 1 , 1 0 ) ,
589 Gender = ” Male ” ,
590 Email = ”bob . j@email . com” ,
591 Phone = ” 5551234567 ” ,
592 Course = ” E n g i n e e r i n g ” ,
593 Semester = 4 ,
594 Attendance = 7 5 ,
595 Marks = 8 2 ,
596 Hostel = true ,
597 Scholarship = f a l s e
598 }) ;
599 }
600

601 p r i v a t e v o i d UpdateStudentGrid ( L i s t <Student> s t u d e n t L i s t =


null )
602 {
603 i f ( s t u d e n t L i s t == n u l l )
604 studentList = students ;
605

606 dgvStudents . DataSource = n u l l ;


607 dgvStudents . DataSource = s t u d e n t L i s t ;
608

609 // Format columns


610 i f ( dgvStudents . Columns . Count > 0 )
611 {
612 dgvStudents . Columns [ ” Id ” ] . Width = 4 0 ;
613 dgvStudents . Columns [ ” FullName ” ] . Width = 1 2 0 ;
2.7. STUDENT INFORMATION MANAGEMENT SYSTEM 51

614 dgvStudents . Columns [ ” Course ” ] . Width = 1 0 0 ;


615 dgvStudents . Columns [ ” S e m e s t e r ” ] . Width = 6 0 ;
616 dgvStudents . Columns [ ” Attendance ” ] . Width = 7 0 ;
617 dgvStudents . Columns [ ”Marks” ] . Width = 6 0 ;
618 dgvStudents . Columns [ ” H o s t e l ” ] . Width = 5 0 ;
619 dgvStudents . Columns [ ” S c h o l a r s h i p ” ] . Width = 7 0 ;
620 dgvStudents . Columns [ ” Email ” ] . V i s i b l e = f a l s e ; // Hide some
columns f o r b r e v i t y
621 dgvStudents . Columns [ ”Phone” ] . V i s i b l e = f a l s e ;
622 }
623

624 l b l S t a t u s . Text = $ ” T o t a l S t u d e n t s : { s t u d e n t s . Count} |


Showing : { s t u d e n t L i s t . Count} ” ;
625 UpdateStatistics () ;
626 }
627

628 private void ClearInputFields ( )


629 {
630 t x t S t u d e n t I d . Text = ”Auto= g e n e r a t e d ” ;
631 txtFullName . C l e a r ( ) ;
632 txtEmail . Clear ( ) ;
633 txtPhone . C l e a r ( ) ;
634 dtpBirthDate . Value = DateTime . Today . AddYears ( = 18) ;
635 rbMale . Checked = t r u e ;
636 cboCourse . S e l e c t e d I n d e x = = 1;
637 c b o S e m e s t e r . S e l e c t e d I n d e x = = 1;
638 nudAttendance . Value = 7 5 ;
639 nudMarks . Value = 6 0 ;
640 c h k H o s t e l . Checked = f a l s e ;
641 c h k S c h o l a r s h i p . Checked = f a l s e ;
642

643 // Switch t o i n p u t tab


644 tabControl . SelectedIndex = 0;
645 }
646

647 p r i v a t e v o i d BtnAdd Click ( o b j e c t s e n d e r , EventArgs e )


648 {
649 // V a l i d a t e i n p u t s
650 i f ( s t r i n g . IsNullOrWhiteSpace ( txtFullName . Text ) )
651 {
652 MessageBox . Show ( ” P l e a s e e n t e r s t u d e n t name . ” , ” V a l i d a t i o n
Error ” ) ;
653 return ;
654 }
655

656 i f ( cboCourse . S e l e c t e d I n d e x == =1)


657 {
658 MessageBox . Show ( ” P l e a s e s e l e c t a c o u r s e . ” , ” V a l i d a t i o n
Error ” ) ;
659 return ;
660 }
52 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

661

662 i f ( c b o S e m e s t e r . S e l e c t e d I n d e x == =1)
663 {
664 MessageBox . Show ( ” P l e a s e s e l e c t a s e m e s t e r . ” , ” V a l i d a t i o n
Error ” ) ;
665 return ;
666 }
667

668 // C r e a t e new s t u d e n t
669 Student newStudent = new Student
670 {
671 Id = n e x t I d ++,
672 FullName = txtFullName . Text ,
673 BirthDate = dtpBirthDate . Value ,
674 Gender = rbMale . Checked ? ” Male ” : ( rbFemale . Checked ? ”
Female ” : ” Other ” ) ,
675 Email = t x t E m a i l . Text ,
676 Phone = txtPhone . Text ,
677 Course = cboCourse . S e l e c t e d I t e m . T o S t r i n g ( ) ,
678 S e m e s t e r = i n t . Parse ( c b o S e m e s t e r . S e l e c t e d I t e m . T o S t r i n g ( ) ) ,
679 Attendance = ( i n t ) nudAttendance . Value ,
680 Marks = ( i n t ) nudMarks . Value ,
681 H o s t e l = c h k H o s t e l . Checked ,
682 S c h o l a r s h i p = c h k S c h o l a r s h i p . Checked
683 };
684

685 s t u d e n t s . Add( newStudent ) ;


686 UpdateStudentGrid ( ) ;
687

688 MessageBox . Show ( ” Student added s u c c e s s f u l l y ! ” , ” S u c c e s s ” ) ;


689 ClearInputFields () ;
690

691 // Switch t o view tab t o s e e t h e new s t u d e n t


692 tabControl . SelectedIndex = 1;
693 }
694

695 p r i v a t e v o i d B t n D e l e t e C l i c k ( o b j e c t s e n d e r , EventArgs e )
696 {
697 i f ( dgvStudents . Sel ec ted Row s . Count > 0 )
698 {
699 Student s e l e c t e d = dgvStudents . S ele ct edR ows [ 0 ] .
DataBoundItem a s Student ;
700

701 D i a l o g R e s u l t r e s u l t = MessageBox . Show (


702 $ ” Are you s u r e you want t o d e l e t e { s e l e c t e d . FullName }? ” ,
703 ” Confirm D e l e t e ” ,
704 MessageBoxButtons . YesNo ,
705 MessageBoxIcon . Q u e s t i o n
706 );
707

708 i f ( r e s u l t == D i a l o g R e s u l t . Yes )
2.7. STUDENT INFORMATION MANAGEMENT SYSTEM 53

709 {
710 s t u d e n t s . Remove ( s e l e c t e d ) ;
711 UpdateStudentGrid ( ) ;
712 l b l S t a t u s . Text = ” Student d e l e t e d s u c c e s s f u l l y ” ;
713 }
714 }
715 else
716 {
717 MessageBox . Show ( ” P l e a s e s e l e c t a s t u d e n t t o d e l e t e . ” , ”No
Selection ”) ;
718 }
719 }
720

721 p r i v a t e void DgvStudents SelectionChanged ( o b j e c t sender ,


EventArgs e )
722 {
723 i f ( dgvStudents . Sel ec ted Row s . Count > 0 )
724 {
725 Student s e l e c t e d = dgvStudents . S ele ct edR ows [ 0 ] .
DataBoundItem a s Student ;
726 l b l S t a t u s . Text = $ ” S e l e c t e d : { s e l e c t e d . FullName } = {
s e l e c t e d . Course } ( S e m e s t er { s e l e c t e d . S e m e s t e r } ) ” ;
727 }
728 }
729

730 p r i v a t e v o i d TxtSearch TextChanged ( o b j e c t s e n d e r , EventArgs e )


731 {
732 FilterStudents () ;
733 }
734

735 private void F i l t e r S t u d e n t s ( )


736 {
737 s t r i n g s e a r c h T e x t = t x t S e a r c h . Text . ToLower ( ) ;
738

739 i f ( s t r i n g . IsNullOrWhiteSpace ( s e a r c h T e x t ) )
740 {
741 UpdateStudentGrid ( ) ;
742 return ;
743 }
744

745 var f i l t e r e d = s t u d e n t s . Where ( s =>


746 s . FullName . ToLower ( ) . C o n t a i n s ( s e a r c h T e x t ) | |
747 s . Email . ToLower ( ) . C o n t a i n s ( s e a r c h T e x t ) | |
748 s . Course . ToLower ( ) . C o n t a i n s ( s e a r c h T e x t )
749 ) . ToList ( ) ;
750

751 UpdateStudentGrid ( f i l t e r e d ) ;
752 }
753

754 p r i v a t e void FilterRadio CheckedChanged ( o b j e c t sender ,


EventArgs e )
54 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

755 {
756 i f ( r b S e a r c h A l l . Checked )
757 {
758 UpdateStudentGrid ( ) ;
759 }
760 }
761

762 p r i v a t e void FilterCombo SelectedIndexChanged ( o b j e c t sender ,


EventArgs e )
763 {
764 i f ( rbSearchByCourse . Checked && c b o S e a r c h C o u r s e . S e l e c t e d I t e m
!= n u l l )
765 {
766 s t r i n g c o u r s e = c bo S e a r c h C o u r s e . S e l e c t e d I t e m . T o S t r i n g ( ) ;
767 var f i l t e r e d = s t u d e n t s . Where ( s => s . Course == c o u r s e ) .
ToList ( ) ;
768 UpdateStudentGrid ( f i l t e r e d ) ;
769 }
770 }
771

772 p r i v a t e v o i d B t n S h o w S t a t s C l i c k ( o b j e c t s e n d e r , EventArgs e )
773 {
774 UpdateStatistics () ;
775 t a b C o n t r o l . S e l e c t e d I n d e x = 2 ; // Switch t o s e a r c h tab
776 }
777

778 private void U p d a te S t a t is t i c s ()


779 {
780 s t a t s L i s t B o x . Items . C l e a r ( ) ;
781

782 i f ( s t u d e n t s . Count == 0 )
783 {
784 s t a t s L i s t B o x . Items . Add( ”No s t u d e n t s t o d i s p l a y s t a t i s t i c s .
”) ;
785 return ;
786 }
787

788 // B a s i c s t a t i s t i c s
789 s t a t s L i s t B o x . Items . Add( $ ” T o t a l S t u d e n t s : { s t u d e n t s . Count} ” ) ;
790 s t a t s L i s t B o x . Items . Add( ” ” ) ;
791

792 // Gender d i s t r i b u t i o n
793 i n t maleCount = s t u d e n t s . Count ( s => s . Gender == ” Male ” ) ;
794 i n t femaleCount = s t u d e n t s . Count ( s => s . Gender == ” Female ” ) ;
795 i n t otherCount = s t u d e n t s . Count ( s => s . Gender == ” Other ” ) ;
796

797 s t a t s L i s t B o x . Items . Add( $ ” Male S t u d e n t s : { maleCount } ( {


maleCount * 100 / s t u d e n t s . Count}%)” ) ;
798 s t a t s L i s t B o x . Items . Add( $ ” Female S t u d e n t s : { femaleCount } ( {
femaleCount * 100 / s t u d e n t s . Count}%)” ) ;
799 s t a t s L i s t B o x . Items . Add( $ ” Other : { otherCount } ( { otherCount *
2.7. STUDENT INFORMATION MANAGEMENT SYSTEM 55

100 / s t u d e n t s . Count}%)” ) ;
800 s t a t s L i s t B o x . Items . Add( ” ” ) ;
801

802 // Course d i s t r i b u t i o n
803 s t a t s L i s t B o x . Items . Add( ” S t u d e n t s by Course : ” ) ;
804 var course Groups = s t u d e n t s . GroupBy ( s => s . Course ) ;
805 f o r e a c h ( var group i n c ourseGroups )
806 {
807 s t a t s L i s t B o x . Items . Add( $ ” { group . Key } : { group . Count ( ) } ” ) ;
808 }
809 s t a t s L i s t B o x . Items . Add( ” ” ) ;
810

811 // Academic a v e r a g e s
812 d o u b l e avgAttendance = s t u d e n t s . Average ( s => s . Attendance ) ;
813 d o u b l e avgMarks = s t u d e n t s . Average ( s => s . Marks ) ;
814

815 s t a t s L i s t B o x . Items . Add( $ ” Average Attendance : { avgAttendance :


F1}%” ) ;
816 s t a t s L i s t B o x . Items . Add( $ ” Average Marks : { avgMarks : F1}%” ) ;
817 s t a t s L i s t B o x . Items . Add( ” ” ) ;
818

819 // H o s t e l and S c h o l a r s h i p
820 i n t h o s t e l C o u n t = s t u d e n t s . Count ( s => s . H o s t e l ) ;
821 i n t s c h o l a r s h i p C o u n t = s t u d e n t s . Count ( s => s . S c h o l a r s h i p ) ;
822

823 s t a t s L i s t B o x . Items . Add( $ ” H o s t e l R e s i d e n t s : { h o s t e l C o u n t } ” ) ;


824 s t a t s L i s t B o x . Items . Add( $ ” S c h o l a r s h i p H o l d e r s : {
scholarshipCount }” ) ;
825 }
826

827 p r i v a t e v o i d B t n E x p o r t C l i c k ( o b j e c t s e n d e r , EventArgs e )
828 {
829 S a v e F i l e D i a l o g s a v e D i a l o g = new S a v e F i l e D i a l o g ( ) ;
830 s a v e D i a l o g . F i l t e r = ”CSV f i l e s ( * . c s v ) | * . c s v ” ;
831 s a v e D i a l o g . FileName = $ ” S t u d e n t s {DateTime . Now : yyyyMMdd } . c s v
”;
832

833 i f ( s a v e D i a l o g . ShowDialog ( ) == D i a l o g R e s u l t .OK)


834 {
835 try
836 {
837 u s i n g ( System . IO . StreamWriter sw = new System . IO .
StreamWriter ( s a v e D i a l o g . FileName ) )
838 {
839 // Write h e a d e r s
840 sw . WriteLine ( ” Id , FullName , Gender , Course , Semester ,
Attendance , Marks , H o s t e l , S c h o l a r s h i p ” ) ;
841

842 // Write data


843 f o r e a c h ( Student s i n s t u d e n t s )
844 {
56 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES

845 sw . WriteLine ( $ ” { s . Id } , { s . FullName } , { s . Gender } , { s .


Course } , { s . S e m e s t e r } , { s . Attendance } , { s . Marks } , { s . H o s t e l } , { s .
S c h o l a r s h i p }” ) ;
846 }
847 }
848

849 MessageBox . Show ( $ ” Data e x p o r t e d s u c c e s s f u l l y t o {


s a v e D i a l o g . FileName } ” , ” Export Complete ” ) ;
850 }
851 c a t c h ( E x c e p t i o n ex )
852 {
853 MessageBox . Show ( $ ” E r r o r e x p o r t i n g data : { ex . Message } ” , ”
Export E r r o r ” ) ;
854 }
855 }
856 }
857 }
858

859 // Student c l a s s f o r data b i n d i n g


860 p u b l i c c l a s s Student
861 {
862 p u b l i c i n t Id { g e t ; s e t ; }
863 p u b l i c s t r i n g FullName { g e t ; s e t ; }
864 p u b l i c DateTime BirthDate { g e t ; s e t ; }
865 p u b l i c s t r i n g Gender { g e t ; s e t ; }
866 p u b l i c s t r i n g Email { g e t ; s e t ; }
867 p u b l i c s t r i n g Phone { g e t ; s e t ; }
868 p u b l i c s t r i n g Course { g e t ; s e t ; }
869 p u b l i c i n t Semester { get ; s e t ; }
870 p u b l i c i n t Attendance { g e t ; s e t ; }
871 p u b l i c i n t Marks { g e t ; s e t ; }
872 public bool Hostel { get ; set ; }
873 public bool Scholarship { get ; set ; }
874 }
875

876 // Program c l a s s t o run t h e a p p l i c a t i o n


877 s t a t i c c l a s s Program
878 {
879 [ STAThread ]
880 s t a t i c v o i d Main ( )
881 {
882 Application . EnableVisualStyles () ;
883 Application . SetCompatibleTextRenderingDefault ( f a l s e ) ;
884 A p p l i c a t i o n . Run( new StudentInfoForm ( ) ) ;
885 }
886 }
887 }

Listing 2.24: Student Information System - Main Form


2.7. STUDENT INFORMATION MANAGEMENT SYSTEM 57

2.7.3 How to Run


1. Create a new Windows Forms App (.NET Framework or .NET Core) project in
Visual Studio

2. Replace the contents of [Link] with the code above

3. Rename [Link] to [Link] if desired

4. Build and run the application


58 CHAPTER 2. UI CONTROLS AND THEIR PROPERTIES
Chapter 3

DataTable and DataGridView

3.1 Introduction to DataTable


The DataTable is a fundamental class in the [Link] namespace that represents an
in-memory cache of data in tabular format with rows and columns, similar to a database
table or spreadsheet. It enables disconnected data architecture, allowing you to work
with data independently of the data source.

3.1.1 Core Concepts


ˆ Columns (DataColumn objects): Define the table schema—name, data type, and
constraints. A DataTable has a Columns collection. Properties include DataType,
ColumnName, AllowDBNull, Unique, and AutoIncrement.

ˆ Rows (DataRow objects): Represent actual data values. A DataTable has a Rows
collection for adding, removing, and accessing rows.

3.1.2 Creating and Populating a DataTable

1 // Create DataTable
2 DataTable studentTable = new DataTable ( " Students " ) ;
3
4 // Define columns
5 studentTable . Columns . Add ( " StudentID " , typeof ( int ) ) ;
6 studentTable . Columns . Add ( " Name " , typeof ( string ) ) ;
7 studentTable . Columns . Add ( " Major " , typeof ( string ) ) ;
8
9 // Set primary key
10 studentTable . PrimaryKey = new DataColumn [] { studentTable . Columns [ "
StudentID " ] };
11
12 // Add rows
13 studentTable . Rows . Add (101 , " Alice Smith " , " Computer Science " ) ;
14 studentTable . Rows . Add (102 , " Bob Johnson " , " Electrical Engineering " ) ;
Listing 3.1: Creating and populating a DataTable

59
60 CHAPTER 3. DATATABLE AND DATAGRIDVIEW

3.1.3 Accessing and Modifying Data

1 // Iterate through rows


2 foreach ( DataRow row in studentTable . Rows )
3 {
4 Console . WriteLine ( $ " { row [ " StudentID " ]}: { row [ " Name " ]} - { row [ " Major
" ]} " ) ;
5 }
6
7 // Access specific value
8 string name = studentTable . Rows [0][ " Name " ]. ToString () ;
9
10 // Modify data
11 studentTable . Rows [0][ " Major " ] = " Software Engineering " ;
12

13 // Remove rows
14 studentTable . Rows . Remove ( studentTable . Rows [1]) ; // Remove second row
15 // studentTable . Rows [0]. Delete () ; // Mark for deletion ( call
AcceptChanges to finalize )
Listing 3.2: Working with DataTable rows

3.1.4 Common Operations


ˆ Filtering: Use Select() method with filter expressions
ˆ Sorting: Pass sort strings to Select()
ˆ Searching: Find rows by primary key using [Link]()
ˆ Data Binding: Bind directly to Windows Forms controls like DataGridView
1 // Filtering and sorting
2 DataRow [] filteredRows = studentTable . Select ( " Major = ’ Computer
Science ’ " , " Name ASC " ) ;
3
4 // Find by primary key
5 DataRow foundRow = studentTable . Rows . Find (101) ;
6
7 // Get computed values
8 int totalStudents = studentTable . Rows . Count ;
Listing 3.3: Common DataTable operations

3.1.5 Binding a DataTable to UI Controls


The DataTable easily binds to Windows Forms controls like DataGridView, ListBox,
and ComboBox by setting the DataSource property:
1 dataGridView1 . DataSource = studentTable ; // or studentTable .
DefaultView
Listing 3.4: Binding DataTable to DataGridView
3.2. DATAGRIDVIEW EVENTS 61

3.2 DataGridView Events


The DataGridView provides events to respond to user interactions and data changes.

3.2.1 Cell Interaction Events


ˆ CellClick: Fires when a cell is clicked. Provides DataGridViewCellEventArgs
with row and column indices.

ˆ CellDoubleClick: Fires on double-click.


ˆ CellMouseEnter/CellMouseLeave: Mouse enters/leaves a cell.
ˆ CellMouseDown/CellMouseUp: Mouse button pressed/released over a cell.
1 private void d a t a G r i d V i e w 1 _ C e l l C l i c k ( object sender ,
DataGridViewCellEventArgs e)
2 {
3 // Ensure valid cell ( not header )
4 if ( e . RowIndex >= 0 && e . ColumnIndex >= 0)
5 {
6 object value = dataGridView1 . Rows [ e . RowIndex ]. Cells [ e . ColumnIndex
]. Value ;
7 MessageBox . Show ( $ " Value : { value } " ) ;
8 }
9 }
Listing 3.5: Handling CellClick Event

3.2.2 Cell Editing Events


These events manage the editing lifecycle:

ˆ CellBeginEdit: Fires when a cell enters edit mode. Can cancel editing via DataGridViewCellCanc
ˆ CellEndEdit: Fires when editing completes.
ˆ CellValidating: Fires before changes are committed. Used for validation—set
[Link] = true to reject invalid input.

ˆ CellValueChanged: Fires after cell value changes.


1 private void d a t a G r i d V i e w 1 _ C e l l V a l i d a t i n g ( object sender ,
DataGridViewCellValidatingEventArgs e)
2 {
3 // Validate Age column ( index 2)
4 if ( e . ColumnIndex == 2)
5 {
6 if (! int . TryParse ( e . FormattedValue . ToString () , out int age ) ||
age < 0 || age > 120)
7 {
8 e . Cancel = true ; // Reject invalid input
9 dataGridView1 . Rows [ e . RowIndex ]. ErrorText = " Age must be 0 -120 " ;
10 }
62 CHAPTER 3. DATATABLE AND DATAGRIDVIEW

11 else
12 {
13 dataGridView1 . Rows [ e . RowIndex ]. ErrorText = " " ; // Clear error
14 }
15 }
16 }
Listing 3.6: Validating cell input

3.2.3 Row Interaction Events


ˆ RowEnter/RowLeave: Fire when current row changes.
ˆ UserAddedRow/UserDeletedRow: Fire after user adds/deletes a row.
3.2.4 Column and Header Events
ˆ ColumnHeaderMouseClick: Fires when column header clicked—useful for custom
sorting.

ˆ ColumnWidthChanged, RowHeaderMouseClick: Respond to column/header interac-


tions.

3.2.5 Data Binding and Error Events


ˆ DataError: Fires when data binding errors occur—handle to prevent crashes.
ˆ DataSourceChanged: Fires when DataSource property changes.
3.3 DataGridView Columns
Columns define the structure and display of data in a DataGridView, representing fields
from the data source.

3.3.1 Column Types


ˆ DataGridViewTextBoxColumn: Default column for text and numeric data
ˆ DataGridViewCheckBoxColumn: Displays boolean values as checkboxes
ˆ DataGridViewComboBoxColumn: Shows dropdown lists for predefined options
ˆ DataGridViewImageColumn: Displays images
ˆ DataGridViewButtonColumn: Shows clickable buttons in cells
ˆ DataGridViewLinkColumn: Displays text as hyperlinks
3.3. DATAGRIDVIEW COLUMNS 63

3.3.2 Adding Columns Programmatically

1 // Text column
2 D a t a G r i d V i e w T e x t B o x C o l u m n nameColumn = new D a t a G r i d V i e w T e x t B o x C o l u m n
() ;
3 nameColumn . Name = " NameColumn " ;
4 nameColumn . HeaderText = " Student Name " ;
5 nameColumn . DataPropertyName = " Name " ;
6 dataGridView1 . Columns . Add ( nameColumn ) ;
7
8 // CheckBox column
9 D a t a G r i d V i e w C h e c k B o x C o l u m n activeColumn = new
D a t a G r i d V i e w C h e c k B o x C o l u m n () ;
10 activeColumn . Name = " ActiveColumn " ;
11 activeColumn . HeaderText = " Active " ;
12 activeColumn . DataPropertyName = " IsActive " ;
13 dataGridView1 . Columns . Add ( activeColumn ) ;
14
15 // ComboBox column
16 D a t a G r i d V i e w C o m b o B o x C o l u m n majorColumn = new
D a t a G r i d V i e w C o m b o B o x C o l u m n () ;
17 majorColumn . Name = " MajorColumn " ;
18 majorColumn . HeaderText = " Major " ;
19 majorColumn . DataSource = GetMajorsList () ; // List of options
20 majorColumn . DisplayMember = " Name " ;
21 majorColumn . ValueMember = " Id " ;
22 dataGridView1 . Columns . Add ( majorColumn ) ;
Listing 3.7: Adding different column types

3.3.3 Key Column Properties


ˆ Name: Programmatic identifier
ˆ HeaderText: Column header display text
ˆ DataPropertyName: Binds to data source property
ˆ Visible: Show/hide column
ˆ ReadOnly: Prevent editing
ˆ Width, MinimumWidth, MaximumWidth: Size control
ˆ AutoSizeMode: Automatic sizing behavior
ˆ SortMode: Sorting capability
ˆ DefaultCellStyle: Cell appearance defaults
ˆ DisplayIndex: Column order position
64 CHAPTER 3. DATATABLE AND DATAGRIDVIEW

3.4 Customizing DataGridView


3.4.1 Styling Properties
1 // Overall appearance
2 dataGridView1 . BackColor = Color . White ;
3 dataGridView1 . ForeColor = Color . Black ;
4 dataGridView1 . Font = new Font ( " Segoe UI " , 9) ;
5 dataGridView1 . GridColor = Color . LightGray ;
6 dataGridView1 . CellBorderStyle = D a t a G r i d V i e w C e l l B o r d e r S t y l e . Single ;
7
8 // Header styling
9 dataGridView1 . C o l u m n H e a d e r s D e f a u l t C e l l S t y l e . BackColor = Color . Navy ;
10 dataGridView1 . C o l u m n H e a d e r s D e f a u l t C e l l S t y l e . ForeColor = Color . White ;
11 dataGridView1 . C o l u m n H e a d e r s D e f a u l t C e l l S t y l e . Font = new Font ( " Segoe UI
" , 10 , FontStyle . Bold ) ;
12
13 // Alternating rows for readability
14 dataGridView1 . A l t e r n a t i n g R o w s D e f a u l t C e l l S t y l e . BackColor = Color .
AliceBlue ;
15

16 // Selection colors
17 dataGridView1 . DefaultCellStyle . Sel ec ti on Ba ck Co lo r = Color .
CornflowerBlue ;
18 dataGridView1 . DefaultCellStyle . Sel ec ti on Fo re Co lo r = Color . White ;
Listing 3.8: Basic DataGridView styling

3.4.2 Conditional Formatting


Use the CellFormatting event to dynamically style cells based on values:
1 private void d a t a G r i d V i e w 1 _ C e l l F o r m a t t i n g ( object sender ,
DataGridViewCellFormattingEventArgs e)
2 {
3 // Skip header and invalid cells
4 if ( e . RowIndex < 0 || e . ColumnIndex < 0) return ;
5
6 // Format based on Grade column
7 if ( dataGridView1 . Columns [ e . ColumnIndex ]. Name == " Grade " )
8 {
9 string grade = e . Value ?. ToString () ;
10
11 if ( grade == " A " || grade == " B " )
12 {
13 e . CellStyle . BackColor = Color . LightGreen ;
14 e . CellStyle . ForeColor = Color . DarkGreen ;
15 }
16 else if ( grade == " D " || grade == " F " )
17 {
18 e . CellStyle . BackColor = Color . LightCoral ;
19 e . CellStyle . ForeColor = Color . DarkRed ;
20 }
21 }
22 }
Listing 3.9: Conditional formatting based on cell value
3.4. CUSTOMIZING DATAGRIDVIEW 65

3.4.3 Editing Customization


ˆ EditMode: Controls how editing begins (EditOnEnter, EditOnKeystroke, etc.)
ˆ ReadOnly: Set to true to prevent all editing
ˆ BeginEdit()/EndEdit(): Programmatically control editing
66 CHAPTER 3. DATATABLE AND DATAGRIDVIEW
Chapter 4

Dialogs

4.1 Dialogs in Windows Forms


Dialogs are secondary windows that prompt users for input, display information, or allow
choices. Windows Forms provides built-in dialog classes for common tasks.

4.2 MessageBox
The MessageBox displays modal dialogs with text, buttons, and icons, returning a DialogResult
value.

4.2.1 Basic Usage

1 // Simple message
2 MessageBox . Show ( " File saved successfully . " ) ;
3

4 // With title and buttons


5 DialogResult result = MessageBox . Show ( " Save changes ? " , " Confirm " ,
6 Mes sageBo xButt ons . YesNoCancel ) ;
7
8 // With icon
9 MessageBox . Show ( " Error loading file " , " Error " ,
10 Mes sageB oxButt ons . OK , MessageBoxIcon . Error ) ;
11
12 // Question with default button
13 DialogResult response = MessageBox . Show ( " Delete item ? " , " Confirm " ,
14 Mes sageB oxButt ons . YesNo , MessageBoxIcon . Question ,
15 M e s s a g e B o x D e f a u l t B u t t o n . Button2 ) ; // " No " is default
Listing 4.1: MessageBox variations

MessageBoxButtons: OK, OKCancel, YesNo, YesNoCancel, AbortRetryIgnore


MessageBoxIcon: Error, Warning, Information, Question, Stop, Exclamation

4.2.2 Form as Dialog


Any form can be displayed as a modal dialog using ShowDialog().

67
68 CHAPTER 4. DIALOGS

1 // Create custom dialog form with OK / Cancel buttons


2 public class InputDialog : Form
3 {
4 public string EnteredText = > textBox1 . Text ;
5
6 public InputDialog ()
7 {
8 var btnOK = new Button { Text = " OK " , DialogResult = DialogResult
. OK };
9 var btnCancel = new Button { Text = " Cancel " , DialogResult =
DialogResult . Cancel };
10 this . AcceptButton = btnOK ;
11 this . CancelButton = btnCancel ;
12 }
13 }
14
15 // Usage in main form
16 using ( InputDialog dlg = new InputDialog () )
17 {
18 if ( dlg . ShowDialog () == DialogResult . OK )
19 {
20 string input = dlg . EnteredText ;
21 // Use input
22 }
23 }
Listing 4.2: Creating and showing a custom dialog

4.3 Common Dialogs

4.3.1 OpenFileDialog and SaveFileDialog


File dialogs for opening and saving files.
1 OpenFileDialog openDlg = new OpenFileDialog () ;
2 openDlg . Filter = " Text files (*. txt ) |*. txt | All files (*.*) |*.* " ;
3 openDlg . Title = " Select a file " ;
4 openDlg . InitialDirectory = Environment . GetFolderPath ( Environment .
SpecialFolder . MyDocuments ) ;
5 openDlg . Multiselect = false ;
6
7 if ( openDlg . ShowDialog () == DialogResult . OK )
8 {
9 string selectedFile = openDlg . FileName ;
10 // Load file
11 }
12
13 SaveFileDialog saveDlg = new SaveFileDialog () ;
14 saveDlg . Filter = " Text files (*. txt ) |*. txt " ;
15 saveDlg . DefaultExt = " txt " ;
16 saveDlg . OverwritePrompt = true ;
17
18 if ( saveDlg . ShowDialog () == DialogResult . OK )
19 {
20 // Save to saveDlg . FileName
4.3. COMMON DIALOGS 69

21 }
Listing 4.3: OpenFileDialog usage
Key Properties:
ˆ Filter: File type filters (e.g., ”Images—*.jpg;*.png”)
ˆ FileName: Selected file path
ˆ InitialDirectory: Starting folder
ˆ Multiselect: Allow multiple file selection (OpenFileDialog only)
ˆ OverwritePrompt: Confirm before overwriting (SaveFileDialog only)
4.3.2 FontDialog
Allows users to select fonts, styles, sizes, and colors.
1 FontDialog fontDlg = new FontDialog () ;
2 fontDlg . Font = textBox1 . Font ;
3 fontDlg . Color = textBox1 . ForeColor ;
4 fontDlg . ShowColor = true ;
5 fontDlg . ShowEffects = true ;
6 fontDlg . MaxSize = 24;
7 fontDlg . MinSize = 8;
8
9 if ( fontDlg . ShowDialog () == DialogResult . OK )
10 {
11 textBox1 . Font = fontDlg . Font ;
12 textBox1 . ForeColor = fontDlg . Color ;
13 }
Listing 4.4: FontDialog usage
Key Properties:
ˆ Font, Color: Selected font and color
ˆ ShowColor, ShowEffects: Toggle color and effect options
ˆ MaxSize, MinSize: Font size limits
4.3.3 ColorDialog
Provides color selection with basic and custom colors.
1 ColorDialog colorDlg = new ColorDialog () ;
2 colorDlg . Color = panel1 . BackColor ;
3 colorDlg . AllowFullOpen = true ; // Allow custom colors
4 colorDlg . AnyColor = true ;
5 colorDlg . CustomColors = new int [] {
6 Color . Red . ToArgb () ,
7 Color . Green . ToArgb ()
8 };
9
10 if ( colorDlg . ShowDialog () == DialogResult . OK )
11 {
70 CHAPTER 4. DIALOGS

12 panel1 . BackColor = colorDlg . Color ;


13 }
Listing 4.5: ColorDialog usage
Key Properties:
ˆ Color: Selected color
ˆ AllowFullOpen: Enable/disable custom color section
ˆ CustomColors: Array of preset custom colors
ˆ FullOpen: Show custom colors section expanded
4.3.4 Print Dialogs
PrintDialog: Select printer, copies, and print range.
1 PrintDocument printDoc = new PrintDocument () ;
2 PrintDialog printDlg = new PrintDialog () ;
3 printDlg . Document = printDoc ;
4 printDlg . AllowPages = true ;
5 printDlg . AllowSelection = true ;
6
7 if ( printDlg . ShowDialog () == DialogResult . OK )
8 {
9 printDoc . Print () ; // Start printing
10 }
Listing 4.6: PrintDialog usage
PrintPreviewDialog: Preview document before printing.
1 P ri nt Pr ev ie wD ia lo g previewDlg = new Pri nt Pr ev ie wD ia lo g () ;
2 previewDlg . Document = printDoc ;
3 previewDlg . UseAntiAlias = true ;
4 previewDlg . ShowDialog () ; // Show preview window
Listing 4.7: PrintPreviewDialog usage
PageSetupDialog: Configure page margins, orientation, and paper size.
1 PageSetupDialog pageSetupDlg = new PageSetupDialog () ;
2 pageSetupDlg . Document = printDoc ;
3 pageSetupDlg . AllowMargins = true ;
4 pageSetupDlg . AllowOrientation = true ;
5
6 if ( pageSetupDlg . ShowDialog () == DialogResult . OK )
7 {
8 // Page settings updated in printDoc
9 }
Listing 4.8: PageSetupDialog usage

4.4 Text Editor


4.4.1 Project Description
A basic text editor with:
4.4. TEXT EDITOR 71

ˆ Menu bar with File, Edit, and Format options


ˆ RichTextBox for text editing
ˆ Status bar showing current font and color
ˆ Demonstrates MessageBox, OpenFileDialog, SaveFileDialog, FontDialog, ColorDia-
log, and Print dialogs

4.4.2 Complete Code

1 using System ;
2 using System . Drawing ;
3 using System . Drawing . P r i n t i n g ;
4 using System . IO ;
5 using System . Windows . Forms ;
6

7 namespace DialogDemoApp
8 {
9 p u b l i c c l a s s TextEditorForm : Form
10 {
11 // C o n t r o l s
12 p r i v a t e MenuStrip menuStrip ;
13 p r i v a t e RichTextBox richTextBox ;
14 private StatusStrip statusStrip ;
15 private ToolStripStatusLabel lblStatus ;
16 private ToolStripStatusLabel lblFontInfo ;
17

18 // D i a l o g s
19 p r i v a t e OpenFileDialog openFileDialog ;
20 private SaveFileDialog saveFileDialog ;
21 p r i v a t e FontDialog f o n t D i a l o g ;
22 private ColorDialog colorDialog ;
23 p r i v a t e PrintDocument printDocument ;
24 private PrintDialog printDialog ;
25 private PrintPreviewDialog printPreviewDialog ;
26 p r i v a t e PageSetupDialog p a g e S e t u p D i a l o g ;
27

28 p u b l i c TextEditorForm ( )
29 {
30 InitializeComponents () ;
31 SetupMenu ( ) ;
32 SetupStatusBar ( ) ;
33 }
34

35 private void InitializeComponents ()


36 {
37 // Form s e t t i n g s
38 t h i s . Text = ” Text E d i t o r with D i a l o g s ” ;
39 t h i s . S i z e = new S i z e ( 8 0 0 , 6 0 0 ) ;
40 t h i s . S t a r t P o s i t i o n = FormStartPosition . CenterScreen ;
72 CHAPTER 4. DIALOGS

41 t h i s . IsMdiContainer = f a l s e ;
42

43 // RichTextBox
44 richTextBox = new RichTextBox ( ) ;
45 richTextBox . Dock = DockStyle . F i l l ;
46 richTextBox . Font = new Font ( ” A r i a l ” , 1 1 ) ;
47 richTextBox . Text = ”Type your t e x t h e r e . . . \ n\ nUse t h e F i l e ,
Edit , and Format menus t o e x p l o r e d i f f e r e n t d i a l o g s . ” ;
48

49 // MenuStrip
50 menuStrip = new MenuStrip ( ) ;
51

52 // I n i t i a l i z e d i a l o g s
53 o p e n F i l e D i a l o g = new O p e n F i l e D i a l o g ( ) ;
54 s a v e F i l e D i a l o g = new S a v e F i l e D i a l o g ( ) ;
55 f o n t D i a l o g = new FontDialog ( ) ;
56 c o l o r D i a l o g = new C o l o r D i a l o g ( ) ;
57 printDocument = new PrintDocument ( ) ;
58 p r i n t D i a l o g = new P r i n t D i a l o g ( ) ;
59 p r i n t P r e v i e w D i a l o g = new P r i n t P r e v i e w D i a l o g ( ) ;
60 p a g e S e t u p D i a l o g = new PageSetupDialog ( ) ;
61

62 // C o n f i g u r e d i a l o g s
63 o p e n F i l e D i a l o g . F i l t e r = ” Rich Text F i l e s ( * . r t f ) | * . r t f | Text
Files (*. txt ) | * . txt | All Files (*.*) | * . * ” ;
64 o p e n F i l e D i a l o g . T i t l e = ”Open Document” ;
65

66 s a v e F i l e D i a l o g . F i l t e r = ” Rich Text F i l e s ( * . r t f ) | * . r t f | Text


Files (*. txt ) | * . txt ” ;
67 s a v e F i l e D i a l o g . T i t l e = ” Save Document” ;
68 s ave Fi leD ia log . DefaultExt = ” r t f ” ;
69 s a v e F i l e D i a l o g . AddExtension = t r u e ;
70

71 f o n t D i a l o g . ShowColor = t r u e ;
72 fontDialog . ShowEffects = true ;
73

74 p r i n t D i a l o g . Document = printDocument ;
75 p r i n t P r e v i e w D i a l o g . Document = printDocument ;
76 p a g e S e t u p D i a l o g . Document = printDocument ;
77

78 // Add c o n t r o l s t o form
79 t h i s . C o n t r o l s . Add( richTextBox ) ;
80 t h i s . C o n t r o l s . Add( menuStrip ) ;
81 t h i s . MainMenuStrip = menuStrip ;
82 }
83

84 p r i v a t e v o i d SetupMenu ( )
85 {
86 // F i l e Menu
87 ToolStripMenuItem f i l e M e n u = new ToolStripMenuItem ( ”&F i l e ” ) ;
88
4.4. TEXT EDITOR 73

89 ToolStripMenuItem newItem = new ToolStripMenuItem ( ”&New” ) ;


90 newItem . ShortcutKeys = Keys . C o n t r o l | Keys .N;
91 newItem . C l i c k += ( s , e ) => NewDocument ( ) ;
92

93 ToolStripMenuItem openItem = new ToolStripMenuItem ( ”&Open . . .


”) ;
94 openItem . ShortcutKeys = Keys . C o n t r o l | Keys .O;
95 openItem . C l i c k += ( s , e ) => OpenFile ( ) ;
96

97 ToolStripMenuItem s a v e I t e m = new ToolStripMenuItem ( ”&Save ” ) ;


98 s a v e I t e m . ShortcutKeys = Keys . C o n t r o l | Keys . S ;
99 s a v e I t e m . C l i c k += ( s , e ) => S a v e F i l e ( ) ;
100

101 ToolStripMenuItem saveAsItem = new ToolStripMenuItem ( ” Save &


As . . . ” ) ;
102 saveAsItem . C l i c k += ( s , e ) => S a v e F i l e A s ( ) ;
103

104 T o o l S t r i p S e p a r a t o r s e p 1 = new T o o l S t r i p S e p a r a t o r ( ) ;
105

106 ToolStripMenuItem pageSetupItem = new ToolStripMenuItem ( ”


Page S e t&up . . . ” ) ;
107 pageSetupItem . C l i c k += ( s , e ) => ShowPageSetup ( ) ;
108

109 ToolStripMenuItem p r i n t P r e v i e w I t e m = new ToolStripMenuItem ( ”


P r i n t Pre&view . . . ” ) ;
110 p r i n t P r e v i e w I t e m . C l i c k += ( s , e ) => ShowPrintPreview ( ) ;
111

112 ToolStripMenuItem p r i n t I t e m = new ToolStripMenuItem ( ”&P r i n t


. . . ”) ;
113 p r i n t I t e m . ShortcutKeys = Keys . C o n t r o l | Keys . P ;
114 p r i n t I t e m . C l i c k += ( s , e ) => ShowPrintDialog ( ) ;
115

116 T o o l S t r i p S e p a r a t o r s e p 2 = new T o o l S t r i p S e p a r a t o r ( ) ;
117

118 ToolStripMenuItem e x i t I t e m = new ToolStripMenuItem ( ”E&x i t ” ) ;


119 e x i t I t e m . ShortcutKeys = Keys . Alt | Keys . F4 ;
120 e x i t I t e m . C l i c k += ( s , e ) => A p p l i c a t i o n . E x i t ( ) ;
121

122 f i l e M e n u . DropDownItems . AddRange ( new T o o l S t r i p I t e m [ ] {


123 newItem , openItem , saveItem , saveAsItem , sep1 ,
124 pageSetupItem , p r i n t P r e v i e w I t e m , p r i n t I t e m , sep2 , e x i t I t e m
125 }) ;
126

127 // E dit Menu


128 ToolStripMenuItem editMenu = new ToolStripMenuItem ( ”&Edi t ” ) ;
129

130 ToolStripMenuItem cutItem = new ToolStripMenuItem ( ”Cu&t ” ) ;


131 cutItem . ShortcutKeys = Keys . C o n t r o l | Keys .X;
132 cutItem . C l i c k += ( s , e ) => richTextBox . Cut ( ) ;
133

134 ToolStripMenuItem copyItem = new ToolStripMenuItem ( ”&Copy” ) ;


74 CHAPTER 4. DIALOGS

135 copyItem . ShortcutKeys = Keys . C o n t r o l | Keys . C ;


136 copyItem . C l i c k += ( s , e ) => richTextBox . Copy ( ) ;
137

138 ToolStripMenuItem p a s t e I t e m = new ToolStripMenuItem ( ”&Paste ”


);
139 p a s t e I t e m . ShortcutKeys = Keys . C o n t r o l | Keys .V;
140 p a s t e I t e m . C l i c k += ( s , e ) => richTextBox . Paste ( ) ;
141

142 T o o l S t r i p S e p a r a t o r s e p 3 = new T o o l S t r i p S e p a r a t o r ( ) ;
143

144 ToolStripMenuItem s e l e c t A l l I t e m = new ToolStripMenuItem ( ”


S e l e c t &A l l ” ) ;
145 s e l e c t A l l I t e m . ShortcutKeys = Keys . C o n t r o l | Keys .A;
146 s e l e c t A l l I t e m . C l i c k += ( s , e ) => richTextBox . S e l e c t A l l ( ) ;
147

148 editMenu . DropDownItems . AddRange ( new T o o l S t r i p I t e m [ ] {


149 cutItem , copyItem , pasteItem , sep3 , s e l e c t A l l I t e m
150 }) ;
151

152 // Format Menu


153 ToolStripMenuItem formatMenu = new ToolStripMenuItem ( ”F&
ormat ” ) ;
154

155 ToolStripMenuItem f o n t I t e m = new ToolStripMenuItem ( ”&Font . . .


”) ;
156 f o n t I t e m . C l i c k += ( s , e ) => ShowFontDialog ( ) ;
157

158 ToolStripMenuItem c o l o r I t e m = new ToolStripMenuItem ( ”&C o l o r


. . . ”) ;
159 c o l o r I t e m . C l i c k += ( s , e ) => ShowColorDialog ( ) ;
160

161 ToolStripMenuItem bgColorItem = new ToolStripMenuItem ( ”&


Background C o l o r . . . ” ) ;
162 bgColorItem . C l i c k += ( s , e ) => ShowBgColorDialog ( ) ;
163

164 formatMenu . DropDownItems . AddRange ( new T o o l S t r i p I t e m [ ] {


165 f o n t I t e m , c o l o r I t e m , bgColorItem
166 }) ;
167

168 // Help Menu


169 ToolStripMenuItem helpMenu = new ToolStripMenuItem ( ”&Help ” ) ;
170

171 ToolStripMenuItem aboutItem = new ToolStripMenuItem ( ”&About”


);
172 aboutItem . C l i c k += ( s , e ) => ShowAboutDialog ( ) ;
173

174 helpMenu . DropDownItems . Add( aboutItem ) ;


175

176 // Add a l l menus


177 menuStrip . Items . AddRange ( new T o o l S t r i p I t e m [ ] {
178 f i l e M e n u , editMenu , formatMenu , helpMenu
4.4. TEXT EDITOR 75

179 }) ;
180 }
181

182 p r i v a t e void SetupStatusBar ( )


183 {
184 s t a t u s S t r i p = new S t a t u s S t r i p ( ) ;
185

186 l b l S t a t u s = new T o o l S t r i p S t a t u s L a b e l ( ”Ready” ) ;


187 l b l S t a t u s . Spring = true ;
188 l b l S t a t u s . TextAlign = ContentAlignment . M i d d l e L e f t ;
189

190 l b l F o n t I n f o = new T o o l S t r i p S t a t u s L a b e l ( ) ;
191 UpdateFontInfo ( ) ;
192

193 s t a t u s S t r i p . Items . AddRange ( new T o o l S t r i p I t e m [ ] { l b l S t a t u s ,


l b l F o n t I n f o }) ;
194 t h i s . C o n t r o l s . Add( s t a t u s S t r i p ) ;
195 }
196

197 p r i v a t e v o i d UpdateFontInfo ( )
198 {
199 l b l F o n t I n f o . Text = $ ” { richTextBox . Font . Name} , { richTextBox .
Font . S i z e } pt ” ;
200 }
201

202 p r i v a t e v o i d NewDocument ( )
203 {
204 i f ( richTextBox . Text . Length > 0 )
205 {
206 D i a l o g R e s u l t r e s u l t = MessageBox . Show (
207 ” Save c h a n g e s b e f o r e c r e a t i n g new document ? ” ,
208 ”New Document” ,
209 MessageBoxButtons . YesNoCancel ,
210 MessageBoxIcon . Q u e s t i o n ) ;
211

212 i f ( r e s u l t == D i a l o g R e s u l t . Yes )
213 {
214 i f ( ! SaveFile () )
215 return ;
216 }
217 e l s e i f ( r e s u l t == D i a l o g R e s u l t . Cancel )
218 {
219 return ;
220 }
221 }
222

223 richTextBox . C l e a r ( ) ;
224 l b l S t a t u s . Text = ”New document c r e a t e d ” ;
225 }
226

227 p r i v a t e v o i d OpenFile ( )
76 CHAPTER 4. DIALOGS

228 {
229 i f ( o p e n F i l e D i a l o g . ShowDialog ( ) == D i a l o g R e s u l t .OK)
230 {
231 try
232 {
233 s t r i n g e x t = Path . GetExtension ( o p e n F i l e D i a l o g . FileName ) .
ToLower ( ) ;
234

235 i f ( e x t == ” . r t f ” )
236 richTextBox . L o a d F i l e ( o p e n F i l e D i a l o g . FileName ) ;
237 else
238 richTextBox . Text = F i l e . ReadAllText ( o p e n F i l e D i a l o g .
FileName ) ;
239

240 l b l S t a t u s . Text = $ ”Opened : { o p e n F i l e D i a l o g . FileName } ” ;


241 }
242 c a t c h ( E x c e p t i o n ex )
243 {
244 MessageBox . Show ( $ ” E r r o r o p e n i n g f i l e : { ex . Message } ” ,
245 ” E r r o r ” , MessageBoxButtons .OK, MessageBoxIcon . E r r o r ) ;
246 }
247 }
248 }
249

250 private bool SaveFile ()


251 {
252 i f ( s t r i n g . IsNullOrEmpty ( s a v e F i l e D i a l o g . FileName ) )
253 return SaveFileAs ( ) ;
254

255 try
256 {
257 s t r i n g e x t = Path . GetExtension ( s a v e F i l e D i a l o g . FileName ) .
ToLower ( ) ;
258

259 i f ( e x t == ” . r t f ” )
260 richTextBox . S a v e F i l e ( s a v e F i l e D i a l o g . FileName ) ;
261 else
262 F i l e . WriteAllText ( s a v e F i l e D i a l o g . FileName , richTextBox .
Text ) ;
263

264 l b l S t a t u s . Text = $ ” Saved : { s a v e F i l e D i a l o g . FileName } ” ;


265 return true ;
266 }
267 c a t c h ( E x c e p t i o n ex )
268 {
269 MessageBox . Show ( $ ” E r r o r s a v i n g f i l e : { ex . Message } ” ,
270 ” E r r o r ” , MessageBoxButtons .OK, MessageBoxIcon . E r r o r ) ;
271 return f a l s e ;
272 }
273 }
274
4.4. TEXT EDITOR 77

275 p r i v a t e bool SaveFileAs ( )


276 {
277 i f ( s a v e F i l e D i a l o g . ShowDialog ( ) == D i a l o g R e s u l t .OK)
278 return SaveFile () ;
279

280 return f a l s e ;
281 }
282

283 p r i v a t e v o i d ShowFontDialog ( )
284 {
285 f o n t D i a l o g . Font = richTextBox . Font ;
286 f o n t D i a l o g . C o l o r = richTextBox . F o r e C o l o r ;
287

288 i f ( f o n t D i a l o g . ShowDialog ( ) == D i a l o g R e s u l t .OK)


289 {
290 richTextBox . Font = f o n t D i a l o g . Font ;
291 richTextBox . F o r e C o l o r = f o n t D i a l o g . C o l o r ;
292 UpdateFontInfo ( ) ;
293 l b l S t a t u s . Text = ” Font updated ” ;
294 }
295 }
296

297 p r i v a t e v o i d ShowColorDialog ( )
298 {
299 c o l o r D i a l o g . C o l o r = richTextBox . F o r e C o l o r ;
300

301 i f ( c o l o r D i a l o g . ShowDialog ( ) == D i a l o g R e s u l t .OK)


302 {
303 richTextBox . F o r e C o l o r = c o l o r D i a l o g . C o l o r ;
304 l b l S t a t u s . Text = ” Text c o l o r updated ” ;
305 }
306 }
307

308 p r i v a t e v o i d ShowBgColorDialog ( )
309 {
310 c o l o r D i a l o g . C o l o r = richTextBox . BackColor ;
311

312 i f ( c o l o r D i a l o g . ShowDialog ( ) == D i a l o g R e s u l t .OK)


313 {
314 richTextBox . BackColor = c o l o r D i a l o g . C o l o r ;
315 l b l S t a t u s . Text = ” Background c o l o r updated ” ;
316 }
317 }
318

319 p r i v a t e v o i d ShowPageSetup ( )
320 {
321 p a g e S e t u p D i a l o g . ShowDialog ( ) ;
322 }
323

324 p r i v a t e v o i d ShowPrintPreview ( )
325 {
78 CHAPTER 4. DIALOGS

326 p r i n t P r e v i e w D i a l o g . ShowDialog ( ) ;
327 }
328

329 p r i v a t e v o i d ShowPrintDialog ( )
330 {
331 i f ( p r i n t D i a l o g . ShowDialog ( ) == D i a l o g R e s u l t .OK)
332 {
333 // Setup p r i n t e v e n t i f not a l r e a d y done
334 printDocument . PrintPage += PrintDocument PrintPage ;
335 printDocument . P r i n t ( ) ;
336 }
337 }
338

339 p r i v a t e v o i d PrintDocument PrintPage ( o b j e c t s e n d e r ,


PrintPageEventArgs e )
340 {
341 // Simple p r i n t i n g = j u s t p r i n t t h e t e x t
342 e . G ra ph ic s . DrawString ( richTextBox . Text , richTextBox . Font ,
343 Brushes . Black , e . MarginBounds ) ;
344 }
345

346 p r i v a t e v o i d ShowAboutDialog ( )
347 {
348 MessageBox . Show (
349 ” Text E d i t o r with D i a l o g s Demo\n\n” +
350 ” Demonstrates : \ n” +
351 ” MessageBox \n” +
352 ” O p e n F i l e D i a l o g \n” +
353 ” S a v e F i l e D i a l o g \n” +
354 ” FontDialog \n” +
355 ” C o l o r D i a l o g \n” +
356 ” P r i n t D i a l o g \n” +
357 ” P r i n t P r e v i e w D i a l o g \n” +
358 ” PageSetupDialog \n\n” +
359 ”Windows Forms T u t o r i a l ” ,
360 ”About Text E d i t o r ” ,
361 MessageBoxButtons .OK,
362 MessageBoxIcon . I n f o r m a t i o n ) ;
363 }
364 }
365

366 // Program c l a s s
367 s t a t i c c l a s s Program
368 {
369 [ STAThread ]
370 s t a t i c v o i d Main ( )
371 {
372 Application . EnableVisualStyles () ;
373 Application . SetCompatibleTextRenderingDefault ( f a l s e ) ;
374 A p p l i c a t i o n . Run( new TextEditorForm ( ) ) ;
375 }
4.4. TEXT EDITOR 79

376 }
377 }
Listing 4.9: Text Editor with Dialogs - Complete Implementation

4.4.3 How to Run


1. Create a new Windows Forms App project in Visual Studio

2. Replace the contents of [Link] with the code above

3. Build and run the application

4. Explore the menus to see each dialog in action


80 CHAPTER 4. DIALOGS
Chapter 5

Drawing and Mouse Interactions

5.1 Introduction to Drawing in Windows Forms


Windows Forms provides powerful capabilities for custom graphics drawing through
the [Link] namespace, enabling dynamic visuals, custom shapes, charts, and
games.

5.1.1 What is Drawing?


Drawing refers to programmatically rendering graphics (lines, shapes, text, images) onto
a form or control using classes like Graphics, Pen, and Brush.

5.1.2 Key Concepts


ˆ Graphics Object: The drawing surface (Form or Control)
ˆ Pens and Brushes: Draw outlines (Pen) or fill areas (Brush)
ˆ Custom Painting: Override OnPaint method
1 protected override void OnPaint ( PaintEventArgs e )
2 {
3 base . OnPaint ( e ) ;
4 Graphics g = e . Graphics ;
5 Pen blackPen = new Pen ( Color . Black , 3) ;
6 g . DrawLine ( blackPen , 20 , 20 , 200 , 20) ;
7 blackPen . Dispose () ;
8 }
Listing 5.1: Basic drawing structure

5.2 Drawing Rectangles


5.2.1 DrawRectangle (Outline)

81
82 CHAPTER 5. DRAWING AND MOUSE INTERACTIONS

1 protected override void OnPaint ( PaintEventArgs e )


2 {
3 base . OnPaint ( e ) ;
4 Graphics g = e . Graphics ;
5
6 using ( Pen bluePen = new Pen ( Color . Blue , 2) )
7 {
8 // Method 1: Using coordinates
9 g . DrawRectangle ( bluePen , 50 , 50 , 150 , 100) ;
10
11 // Method 2: Using Rectangle structure
12 Rectangle rect = new Rectangle (220 , 50 , 150 , 100) ;
13 g . DrawRectangle ( bluePen , rect ) ;
14 }
15 }
Listing 5.2: Drawing rectangle outlines

5.2.2 FillRectangle (Solid)

1 protected override void OnPaint ( PaintEventArgs e )


2 {
3 base . OnPaint ( e ) ;
4 Graphics g = e . Graphics ;
5
6 using ( SolidBrush greenBrush = new SolidBrush ( Color . Green ) )
7 {
8 g . FillRectangle ( greenBrush , 60 , 60 , 150 , 100) ;
9 }
10 }
Listing 5.3: Filling rectangles

5.2.3 Brush Types


ˆ SolidBrush: Single color
ˆ LinearGradientBrush: Color gradient
ˆ TextureBrush: Image-based fill
ˆ HatchBrush: Patterned fill
1 using ( Li n e a rG r a di e n tB r u sh gradientBrush = new L in e a rG r a di e n tB r u sh (
2 new Point (0 , 0) , new Point (200 , 0) , Color . Blue , Color . Red ) )
3 {
4 g . FillRectangle ( gradientBrush , 20 , 20 , 200 , 100) ;
5 }
Listing 5.4: Gradient fill
5.3. DRAWING ELLIPSES AND CIRCLES 83

5.3 Drawing Ellipses and Circles


5.3.1 DrawEllipse

1 protected override void OnPaint ( PaintEventArgs e )


2 {
3 base . OnPaint ( e ) ;
4 Graphics g = e . Graphics ;
5
6 using ( Pen bluePen = new Pen ( Color . Blue , 3) )
7 {
8 // Ellipse ( width != height )
9 g . DrawEllipse ( bluePen , 50 , 50 , 200 , 100) ;
10
11 // Circle ( width == height )
12 g . DrawEllipse ( bluePen , 100 , 200 , 100 , 100) ;
13 }
14

15 // Filled ellipse
16 using ( SolidBrush yellowBrush = new SolidBrush ( Color . Yellow ) )
17 {
18 g . FillEllipse ( yellowBrush , 150 , 300 , 120 , 80) ;
19 }
20 }
Listing 5.5: Ellipses and circles

5.4 Drawing Polygons

1 protected override void OnPaint ( PaintEventArgs e )


2 {
3 base . OnPaint ( e ) ;
4 Graphics g = e . Graphics ;
5
6 // Triangle outline
7 Point [] triangle = { new Point (150 , 50) , new Point (100 , 150) , new
Point (200 , 150) };
8 using ( Pen greenPen = new Pen ( Color . Green , 2) )
9 {
10 g . DrawPolygon ( greenPen , triangle ) ;
11 }
12
13 // Filled pentagon
14 Point [] pentagon = { new Point (150 , 200) , new Point (100 , 250) ,
15 new Point (120 , 320) , new Point (180 , 320) ,
16 new Point (200 , 250) };
17 using ( SolidBrush orangeBrush = new SolidBrush ( Color . Orange ) )
18 {
19 g . FillPolygon ( orangeBrush , pentagon ) ;
20 }
21 }
Listing 5.6: Drawing and filling polygons
84 CHAPTER 5. DRAWING AND MOUSE INTERACTIONS

5.5 Mouse Interactions for Drawing


5.5.1 Mouse Events
ˆ MouseDown: Start drawing
ˆ MouseMove: Continue drawing
ˆ MouseUp: Stop drawing
1 public partial class DrawingForm : Form
2 {
3 private bool isDrawing = false ;
4 private Point previousPoint ;
5
6 public DrawingForm ()
7 {
8 this . MouseDown += (s , e ) = > { isDrawing = true ; previousPoint = e
. Location ; };
9 this . MouseMove += (s , e ) = >
10 {
11 if ( isDrawing )
12 {
13 using ( Graphics g = this . CreateGraphics () )
14 using ( Pen pen = new Pen ( Color . Black , 2) )
15 {
16 g . DrawLine ( pen , previousPoint , e . Location ) ;
17 previousPoint = e . Location ;
18 }
19 }
20 };
21 this . MouseUp += (s , e ) = > isDrawing = false ;
22 }
23 }
Listing 5.7: Freehand drawing with mouse

5.5.2 Common Applications


ˆ Drawing applications
ˆ Signature capture
ˆ Interactive whiteboards
ˆ Drag-based shape creation
5.5.3 Important Notes
ˆ Always dispose of Pen, Brush, and Graphics objects (use using statements)
ˆ For persistent drawing, store points in a collection and redraw in OnPaint
ˆ CreateGraphics() draws temporarily; override OnPaint for persistent graphics
Chapter 6

Interacting with Databases using C#

6.1 Introduction to Databases


A database is an organized collection of structured information stored electronically. In
programming, databases enable applications to persistently store, retrieve, update, and
manage data efficiently.

6.1.1 Core Components


ˆ Tables: Collections of related data organized in rows and columns
ˆ Rows (Records): Individual entries (e.g., one student’s information)
ˆ Columns (Fields): Data attributes (e.g., Name, Age, Address)
Think of a database table as a more powerful version of an Excel spreadsheet with
robust querying capabilities.

6.1.2 Why Applications Need Databases


ˆ Persistence: Data survives beyond application sessions
ˆ Storage: Efficient organization of large data volumes
ˆ Retrieval: Fast searching and filtering of information
ˆ Security: Controlled access to sensitive data
ˆ Scalability: Handle growing data and user demands
6.1.3 Local vs. Remote Databases
ˆ Local Databases: Stored on the same machine (SQLite, SQL Server LocalDB)
ˆ Remote Databases: Hosted on servers (SQL Server, MySQL, PostgreSQL)
85
86 CHAPTER 6. INTERACTING WITH DATABASES USING C#

6.2 [Link]: Bridge Between C# and Databases


[Link] is the primary technology in C# for database interaction, providing classes
to connect, query, and manipulate data.

6.2.1 Key [Link] Classes


ˆ SqlConnection: Opens a connection to SQL Server
ˆ SqlCommand: Executes SQL queries
ˆ SqlDataReader: Reads data row-by-row (forward-only)
ˆ SqlDataAdapter: Bridges database and DataSet/DataTable
ˆ DataTable/DataSet: In-memory data storage
1 using System . Data . SqlClient ;
2
3 string connString = " Server = localhost ; Database = MyDB ; Integrated
Security = True ; " ;
4 using ( SqlConnection conn = new SqlConnection ( connString ) )
5 {
6 conn . Open () ;
7 SqlCommand cmd = new SqlCommand ( " SELECT * FROM Students " , conn ) ;
8 SqlDataReader reader = cmd . ExecuteReader () ;
9
10 while ( reader . Read () )
11 Console . WriteLine ( reader [ " Name " ]) ;
12 }
Listing 6.1: Basic [Link] pattern

6.3 Connecting to a Database


6.3.1 Connection Strings
A connection string contains parameters for database connection:
1 Server = myServer ; Database = myDB ; User Id = myUsername ; Password = myPassword ;
Listing 6.2: Connection string format

ˆ Server: Database server address (localhost, IP, hostname)


ˆ Database: Target database name
ˆ User Id/Password: Authentication credentials
ˆ Integrated Security=True: Use Windows authentication
6.4. EXECUTING SQL COMMANDS 87

1 string connectionString = " Server = localhost ; Database = StudentDB ;


Integrated Security = True ; " ;
2
3 using ( SqlConnection connection = new SqlConnection ( connectionString )
)
4 {
5 try
6 {
7 connection . Open () ;
8 Console . WriteLine ( " Connection successful ! " ) ;
9 // Database operations here
10 }
11 catch ( Exception ex )
12 {
13 Console . WriteLine ( $ " Error : { ex . Message } " ) ;
14 }
15 }
Listing 6.3: Establishing a connection

6.4 Executing SQL Commands


6.4.1 INSERT, UPDATE, DELETE Operations
Use ExecuteNonQuery() for commands that don’t return data.
1 using ( SqlConnection conn = new SqlConnection ( connString ) )
2 {
3 conn . Open () ;
4

5 // INSERT
6 string insert = " INSERT INTO Products ( Name , Price ) VALUES ( ’ Laptop
’ , 999.99) " ;
7 using ( SqlCommand cmd = new SqlCommand ( insert , conn ) )
8 {
9 int rows = cmd . ExecuteNonQuery () ;
10 Console . WriteLine ( $ " { rows } row ( s ) inserted " ) ;
11 }
12
13 // UPDATE
14 string update = " UPDATE Products SET Price = 899.99 WHERE Name = ’
Laptop ’ " ;
15 using ( SqlCommand cmd = new SqlCommand ( update , conn ) )
16 {
17 cmd . ExecuteNonQuery () ;
18 }
19

20 // DELETE
21 string delete = " DELETE FROM Products WHERE Price < 10 " ;
22 using ( SqlCommand cmd = new SqlCommand ( delete , conn ) )
23 {
24 cmd . ExecuteNonQuery () ;
25 }
26 }
Listing 6.4: CRUD operations
88 CHAPTER 6. INTERACTING WITH DATABASES USING C#

6.4.2 Exception Handling


Always wrap database operations in try-catch blocks:
1 try
2 {
3 connection . Open () ;
4 command . ExecuteNonQuery () ;
5 }
6 catch ( SqlException ex )
7 {
8 MessageBox . Show ( $ " Database error : { ex . Message } " ) ;
9 }
10 catch ( Exception ex )
11 {
12 MessageBox . Show ( $ " General error : { ex . Message } " ) ;
13 }
Listing 6.5: Exception handling

6.5 Reading Data (SELECT Queries)


6.5.1 Using SqlDataReader (Row-by-Row)
1 string query = " SELECT Id , Name , Price FROM Products " ;
2
3 using ( SqlConnection conn = new SqlConnection ( connString ) )
4 using ( SqlCommand cmd = new SqlCommand ( query , conn ) )
5 {
6 conn . Open () ;
7 using ( SqlDataReader reader = cmd . ExecuteReader () )
8 {
9 while ( reader . Read () )
10 {
11 int id = reader . GetInt32 (0) ;
12 string name = reader . GetString (1) ;
13 decimal price = reader . GetDecimal (2) ;
14

15 Console . WriteLine ( $ " { id }: { name } - $ { price } " ) ;


16 }
17 }
18 }
Listing 6.6: Reading with SqlDataReader

6.5.2 Loading Data into DataTable


1 DataTable table = new DataTable () ;
2
3 using ( SqlConnection conn = new SqlConnection ( connString ) )
4 {
5 string query = " SELECT Id , Name , Price FROM Products " ;
6 SqlDataAdapter adapter = new SqlDataAdapter ( query , conn ) ;
7 adapter . Fill ( table ) ; // Fills DataTable in memory
8 }
6.6. PARAMETERIZED QUERIES (SECURITY CRITICAL) 89

10 // Work with disconnected data


11 foreach ( DataRow row in table . Rows )
12 {
13 Console . WriteLine ( $ " { row [ " Name " ]}: { row [ " Price " ]} " ) ;
14 }
Listing 6.7: Using DataAdapter and DataTable

6.5.3 Displaying Data in DataGridView

1 private void LoadData ()


2 {
3 string connString = " Server = localhost ; Database = MyDB ; Integrated
Security = True ; " ;
4 string query = " SELECT ProductID , ProductName , UnitPrice FROM
Products " ;
5

6 using ( SqlConnection conn = new SqlConnection ( connString ) )


7 {
8 SqlDataAdapter adapter = new SqlDataAdapter ( query , conn ) ;
9 DataTable table = new DataTable () ;
10 adapter . Fill ( table ) ;
11

12 dataGridView1 . DataSource = table ;


13 dataGridView1 . Au toResi zeColu mns () ;
14 }
15 }
Listing 6.8: Binding to DataGridView

6.6 Parameterized Queries (Security Critical)


6.6.1 Preventing SQL Injection
Never concatenate user input directly into SQL strings. Always use parameters.
1 // DANGEROUS - SQL injection vulnerable
2 string username = txtUsername . Text ;
3 string query = " SELECT * FROM Users WHERE Name = ’" + username + " ’" ;
Listing 6.9: Vulnerable code (DON’T DO THIS)

1 string query = " INSERT INTO Products ( Name , Price ) VALUES ( @name ,
@price ) " ;
2

3 using ( SqlConnection conn = new SqlConnection ( connString ) )


4 using ( SqlCommand cmd = new SqlCommand ( query , conn ) )
5 {
6 // Add parameters - input treated as data , not code
7 cmd . Parameters . AddWithValue ( " @name " , txtName . Text ) ;
8 cmd . Parameters . AddWithValue ( " @price " , numericPrice . Value ) ;
9
10 conn . Open () ;
11 cmd . ExecuteNonQuery () ;
90 CHAPTER 6. INTERACTING WITH DATABASES USING C#

12 }
Listing 6.10: Safe parameterized query

6.6.2 Parameter Data Types


1 cmd . Parameters . Add ( " @id " , SqlDbType . Int ) . Value = 123;
2 cmd . Parameters . Add ( " @date " , SqlDbType . DateTime ) . Value = DateTime . Now ;
3 cmd . Parameters . Add ( " @amount " , SqlDbType . Decimal ) . Value = 99.99 m ;
Listing 6.11: Specifying parameter types

6.7 Updating UI from Database


6.7.1 Refreshing Data After Operations
1 private void R ef re sh Pr od uc tL is t ()
2 {
3 string query = " SELECT Id , Name , Price FROM Products " ;
4

5 using ( SqlConnection conn = new SqlConnection ( connString ) )


6 using ( SqlDataAdapter adapter = new SqlDataAdapter ( query , conn ) )
7 {
8 DataTable table = new DataTable () ;
9 adapter . Fill ( table ) ;
10 dataGridView1 . DataSource = table ; // Refresh grid
11 }
12 }
13
14 private void btnAdd_Click ( object sender , EventArgs e )
15 {
16 // Insert new product
17 string insert = " INSERT INTO Products ( Name , Price ) VALUES ( @name ,
@price ) " ;
18 using ( SqlConnection conn = new SqlConnection ( connString ) )
19 using ( SqlCommand cmd = new SqlCommand ( insert , conn ) )
20 {
21 cmd . Parameters . AddWithValue ( " @name " , txtName . Text ) ;
22 cmd . Parameters . AddWithValue ( " @price " , nudPrice . Value ) ;
23 conn . Open () ;
24 cmd . ExecuteNonQuery () ;
25 }
26

27 R ef re sh Pr od uc tL is t () ; // Refresh display
28 }
Listing 6.12: Refresh DataGridView

6.8 Data Binding with Windows Forms Controls


6.8.1 Binding ComboBox and ListBox
6.9. BEST PRACTICES 91

1 private void LoadCategories ()


2 {
3 string query = " SELECT CategoryID , CategoryName FROM Categories " ;
4
5 using ( SqlConnection conn = new SqlConnection ( connString ) )
6 using ( SqlDataAdapter adapter = new SqlDataAdapter ( query , conn ) )
7 {
8 DataTable dt = new DataTable () ;
9 adapter . Fill ( dt ) ;
10
11 // Bind to ComboBox
12 cboCategory . DataSource = dt ;
13 cboCategory . DisplayMember = " CategoryName " ; // What user sees
14 cboCategory . ValueMember = " CategoryID " ; // Underlying value
15
16 // Same for ListBox
17 lstCategory . DataSource = dt ;
18 lstCategory . DisplayMember = " CategoryName " ;
19 lstCategory . ValueMember = " CategoryID " ;
20 }
21 }
22
23 // Get selected value
24 int selectedId = ( int ) cboCategory . SelectedValue ;
25 string selectedText = cboCategory . Text ;
Listing 6.13: Binding dropdown controls

6.8.2 Binding DataGridView

1 // Set DataSource property directly


2 dataGridView1 . DataSource = dataTable ;
3
4 // Or through BindingSource for more control
5 BindingSource bindingSource = new BindingSource () ;
6 bindingSource . DataSource = dataTable ;
7 dataGridView1 . DataSource = bindingSource ;
Listing 6.14: Simple DataGridView binding

6.9 Best Practices


6.9.1 Always Close Connections (Using Blocks)

1 // GOOD : using block ensures disposal even with exceptions


2 using ( SqlConnection conn = new SqlConnection ( connString ) )
3 using ( SqlCommand cmd = new SqlCommand ( query , conn ) )
4 {
5 conn . Open () ;
6 cmd . ExecuteNonQuery () ;
7 } // Connection closed automatically
8
9 // BAD : Manual close may be skipped if exception occurs
10 SqlConnection conn = new SqlConnection ( connString ) ;
92 CHAPTER 6. INTERACTING WITH DATABASES USING C#

11 conn . Open () ;
12 // ... if exception here , conn . Close () never runs
13 conn . Close () ;
Listing 6.15: Proper connection disposal

6.9.2 Connection Pooling


ˆ Enabled by default in .NET
ˆ Reuses connections for better performance
ˆ Controlled via connection string parameters
1 " Server = myServer ; Database = myDB ; Integrated Security = True ; Max Pool Size
=100; Min Pool Size =10; Connection Timeout =30; "
Listing 6.16: Connection pool settings

6.9.3 Principle of Least Privilege


ˆ Database accounts should have minimal required permissions
ˆ Read-only users should only have SELECT rights
ˆ Data entry users need INSERT/UPDATE only
ˆ Never use admin accounts for application connections
1 -- Read - only user
2 CREATE USER AppReader FOR LOGIN AppReaderLogin ;
3 GRANT SELECT ON dbo . Products TO AppReader ;
4
5 -- Data entry user
6 CREATE USER AppWriter FOR LOGIN AppWriterLogin ;
7 GRANT INSERT , UPDATE ON dbo . Products TO AppWriter ;
Listing 6.17: Grant minimal permissions

6.10 Async Database Operations


6.10.1 Keeping UI Responsive
1 private async void btnLoad_Click ( object sender , EventArgs e )
2 {
3 btnLoad . Enabled = false ;
4 lblStatus . Text = " Loading ... " ;
5
6 try
7 {
8 DataTable data = await LoadDataAsync () ;
9 dataGridView1 . DataSource = data ;
10 lblStatus . Text = $ " Loaded { data . Rows . Count } records " ;
6.11. MASTER-DETAIL RELATIONSHIP 93

11 }
12 catch ( Exception ex )
13 {
14 MessageBox . Show ( $ " Error : { ex . Message } " ) ;
15 }
16 finally
17 {
18 btnLoad . Enabled = true ;
19 }
20 }
21
22 private async Task < DataTable > LoadDataAsync ()
23 {
24 DataTable table = new DataTable () ;
25 string query = " SELECT * FROM Products " ;
26
27 using ( SqlConnection conn = new SqlConnection ( connString ) )
28 {
29 await conn . OpenAsync () ;
30 using ( SqlCommand cmd = new SqlCommand ( query , conn ) )
31 using ( SqlDataReader reader = await cmd . Exe cu te Re ad er As yn c () )
32 {
33 table . Load ( reader ) ;
34 }
35 }
36
37 return table ;
38 }
Listing 6.18: Async database operations

6.11 Master-Detail Relationship


1 private void Se tupMas terDet ail ()
2 {
3 DataSet ds = new DataSet () ;
4
5 // Load categories
6 using ( SqlDataAdapter adapter = new SqlDataAdapter (
7 " SELECT CategoryID , CategoryName FROM Categories " , connString ) )
8 {
9 adapter . Fill ( ds , " Categories " ) ;
10 }
11
12 // Load products
13 using ( SqlDataAdapter adapter = new SqlDataAdapter (
14 " SELECT ProductID , ProductName , CategoryID FROM Products " ,
connString ) )
15 {
16 adapter . Fill ( ds , " Products " ) ;
17 }
18

19 // Create relationship
20 DataRelation relation = new DataRelation (
21 " C at eg or ie sP ro du ct s " ,
22 ds . Tables [ " Categories " ]. Columns [ " CategoryID " ] ,
94 CHAPTER 6. INTERACTING WITH DATABASES USING C#

23 ds . Tables [ " Products " ]. Columns [ " CategoryID " ]) ;


24 ds . Relations . Add ( relation ) ;
25
26 // Bind master grid
27 BindingSource masterSource = new BindingSource ( ds , " Categories " ) ;
28 dgvCategories . DataSource = masterSource ;
29

30 // Bind detail grid through relationship


31 dgvProducts . DataSource = masterSource ;
32 dgvProducts . DataMember = " Cat eg or ie sP ro du ct s " ;
33 }
Listing 6.19: Categories with related products
Chapter 7

Libraries in C#

7.1 Introduction to Libraries


A library is a collection of pre-written code that provides reusable functionality for
common tasks like data processing, UI components, and more. Libraries help developers
avoid reinventing the wheel and promote code reuse across projects.

7.1.1 Types of Libraries in .NET


ˆ Assemblies (DLLs): Compiled code files that can be referenced by applications
ˆ NuGet Packages: A packaging system for distributing .NET libraries
ˆ Framework Libraries: Built-in .NET libraries ([Link], [Link], etc.)
ˆ Static Libraries: Code linked at compile-time (less common in C#)
7.2 Dynamic Link Libraries (DLLs)
DLLs are compiled code files (.dll) that applications can load and execute at runtime.
They are the most common library type in .NET.

7.2.1 Creating a DLL


Create a Class Library project in Visual Studio:
1 namespace MathLibrary
2 {
3 public class Calculator
4 {
5 public int Add ( int a , int b ) = > a + b ;
6 public int Multiply ( int a , int b ) = > a * b ;
7 public int Subtract ( int a , int b ) = > a - b ;
8 }
9 }
Listing 7.1: Simple Calculator Library (DLL)

After compilation, you get [Link].

95
96 CHAPTER 7. LIBRARIES IN C#

7.2.2 Using a DLL in Another Project


1 using MathLibrary ;
2
3 class Program
4 {
5 static void Main ()
6 {
7 Calculator calc = new Calculator () ;
8 int result = calc . Add (5 , 3) ; // Returns 8
9 int product = calc . Multiply (4 , 2) ; // Returns 8
10 Console . WriteLine ( $ " Result : { result } " ) ;
11 }
12 }
Listing 7.2: Referencing and using a DLL
Steps to reference a DLL:

1. Right-click project  Add Reference


2. Browse to the DLL file

3. Click OK

7.2.3 DLL Advantages


ˆ Modularity: Reusable code across multiple projects
ˆ Flexibility: Update DLL without recompiling entire application
ˆ Memory Efficiency: Loaded only when needed
ˆ Versioning: Different versions can coexist
7.3 Static Libraries
Static libraries are embedded into the application executable at compile-time, unlike
DLLs which are loaded at runtime.
1 namespace Utilities
2 {
3 public static class StringHelper
4 {
5 public static string Reverse ( string input )
6 {
7 char [] chars = input . ToCharArray () ;
8 Array . Reverse ( chars ) ;
9 return new string ( chars ) ;
10 }
11
12 public static bool IsPalindrome ( string input )
13 {
14 string reversed = Reverse ( input ) ;
15 return input . Equals ( reversed , StringComparison .
Ord inalIg noreCa se ) ;
7.4. NUGET PACKAGES: THIRD-PARTY LIBRARIES 97

16 }
17 }
18 }
Listing 7.3: Static utility class
Static Library Advantages:

ˆ No runtime loading overhead


ˆ Simpler deployment (single executable)
ˆ No external dependencies
7.4 NuGet Packages: Third-Party Libraries
NuGet is .NET’s package manager for discovering, installing, and updating third-party
libraries.

7.4.1 Installing NuGet Packages


Using .NET CLI:
1 dotnet add package Newtonsoft . Json
2 dotnet add package EntityFramework
3 dotnet add package Dapper
Listing 7.4: Install via command line
Using Visual Studio:

1. Right-click project  Manage NuGet Packages


2. Browse tab  Search for package
3. Click Install

7.4.2 Example: Using [Link]


1 using Newtonsoft . Json ;
2 using System ;
3
4 public class Person
5 {
6 public string Name { get ; set ; }
7 public int Age { get ; set ; }
8 public string Email { get ; set ; }
9 }
10
11 class Program
12 {
13 static void Main ()
14 {
15 // Create object
16 var person = new Person
17 {
98 CHAPTER 7. LIBRARIES IN C#

18 Name = " Alice Smith " ,


19 Age = 28 ,
20 Email = " alice@example . com "
21 };
22
23 // Serialize object to JSON
24 string json = JsonConvert . SerializeObject ( person , Formatting .
Indented ) ;
25 Console . WriteLine ( " Serialized JSON : " ) ;
26 Console . WriteLine ( json ) ;
27
28 // Deserialize JSON back to object
29 Person deserialized = JsonConvert . DeserializeObject < Person >( json )
;
30 Console . WriteLine ( $ " \ nDeserialized : { deserialized . Name } , Age : {
deserialized . Age } " ) ;
31 }
32 }
Listing 7.5: JSON serialization/deserialization
Output:
Serialized JSON:
{
"Name": "Alice Smith",
"Age": 28,
"Email": "alice@[Link]"
}

Deserialized: Alice Smith, Age: 28

7.4.3 Popular NuGet Packages


ˆ [Link]: JSON processing
ˆ Entity Framework Core: Object-relational mapping (ORM)
ˆ Dapper: Lightweight ORM
ˆ EPPlus: Excel file manipulation
ˆ Serilog: Structured logging
ˆ AutoMapper: Object-to-object mapping
7.4.4 Managing NuGet Packages
ˆ Install: Add package to project
ˆ Update: Get newer versions
ˆ Uninstall: Remove package
ˆ Restore: Download all missing packages (when opening a project)

You might also like