0% found this document useful (0 votes)
5 views45 pages

Windows Forms GUI and Database Basics

GUI using Windows Forms and Database Programming: Controls- TextBox, label, Button, checkbox, radiobutton, listbox, comboxbox ,GridView, Datetime picker, Common properties, methods and events , menus, context menus, Menustrip, Graphics and GDI, SDI and MDI, Dialog boxes; Database Programming - Understanding the Role of Managed Provider and ADO.NET Objects , Connecting to Database, Performing CRUD operations.

Uploaded by

Lukman Bagawan
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)
5 views45 pages

Windows Forms GUI and Database Basics

GUI using Windows Forms and Database Programming: Controls- TextBox, label, Button, checkbox, radiobutton, listbox, comboxbox ,GridView, Datetime picker, Common properties, methods and events , menus, context menus, Menustrip, Graphics and GDI, SDI and MDI, Dialog boxes; Database Programming - Understanding the Role of Managed Provider and ADO.NET Objects , Connecting to Database, Performing CRUD operations.

Uploaded by

Lukman Bagawan
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

TUNGAL SCHOOL OF BASICS AND

APPLIED SCIENCES

Notes of Unit-III

GUI using Windows Forms and Database Programming: Controls- TextBox,


label, Button, checkbox, radiobutton, listbox, comboxbox ,GridView,
Datetime picker, Common properties, methods and events , menus, context
menus, Menustrip, Graphics and GDI, SDI and MDI, Dialog boxes; Database
Programming - Understanding the Role of Managed Provider and [Link]
Objects , Connecting to Database, Performing CRUD operations.
TextBox:

A TextBox in Windows Forms is a control that allows users to enter, display, or edit text in
your application.

Namespace:

[Link]

Common Properties of TextBox

Property Description Example


Gets or sets the text [Link] = "John";
Text
displayed in the control.
Identifies the control (used in txtEmail
Name
code).
Allows multiple lines of text
Multiline [Link] = true;
if true.
Masks text with a character [Link] = '*';
PasswordChar
(used for passwords).
Prevents editing if set to
ReadOnly [Link] = true;
true.
Limits the number of [Link] = 50;
MaxLength
characters.
Aligns text inside the box [Link] =
TextAlign [Link];
(Left, Center, Right).
Background color of the text [Link] =
BackColor [Link];
box.
ForeColor Text color. [Link] = [Link];
[Link] = new Font("Arial", 12,
Font Font style for the text. [Link]);
Style of border (Fixed3D, [Link] =
BorderStyle [Link];
FixedSingle, None).
Enables/disables user [Link] = false;
Enabled
interaction.
Visible Shows/hides the control. [Link] = true;

Common Events of TextBox


Event Triggered When... Example Usage
TextChanged The text inside the TextBox changes. Validate input in real time.
KeyPress A key is pressed while the TextBox has focus. Allow only numbers or letters.
KeyDown A key is pressed (before it appears). Detect Enter key.
Event Triggered When... Example Usage
KeyUp A key is released. Custom shortcuts.
GotFocus The TextBox gains focus. Highlight the box.
LostFocus The TextBox loses focus. Validate data after typing.
Click The user clicks the control. Select all text on click.
Enter The control becomes active. Highlight the background.
Leave The control loses focus. Reset background color.

What is a Button?
A Button is a GUI control that lets the user perform an action (like Save, Delete, Exit, etc.)
when clicked.

Namespace:

[Link]

Common Properties of a Button


Property Description Example

Name Identifier used in code. btnSave

The label displayed on the


Text [Link] = "Save";
button.

Whether the button can be


Enabled [Link] = false;
clicked.

Visible Whether the button is shown. [Link] = true;

BackColor Background color. [Link] = [Link];

ForeColor Text color. [Link] = [Link];

[Link] = new Font("Segoe UI", 10,


Font Font style and size of text.
[Link]);

Button’s look (Standard,


FlatStyle [Link] = [Link];
Flat, Popup, System).

Image Image to display on the button. [Link] =


Property Description Example

[Link]("[Link]");

Alignment of image on the [Link] =


ImageAlign [Link];
button.

[Link] =
TextAlign Alignment of text.
[Link];

Dock / Used for layout management


[Link] = [Link];
Anchor (how the button resizes).

Mouse cursor type when


Cursor [Link] = [Link];
hovered.

Order of focus when pressing


TabIndex [Link] = 3;
Tab.

Common Events of a Button


Event Description Example Usage

Run code when user clicks


Click Triggered when the button is clicked.
Save.

When the mouse pointer enters the button


MouseEnter Change color on hover.
area.

When the mouse pointer leaves the button


MouseLeave Revert color after hover.
area.

MouseDown When a mouse button is pressed down. Add pressed effect.

MouseUp When a mouse button is released. Remove pressed effect.

GotFocus When the button gains focus. Highlight button.

LostFocus When the button loses focus. Reset appearance.

KeyDown /
Detect key presses while the button has focus. Trigger on Enter or Space key.
KeyUp
Example: Basic Button Event Handlers
(1) Click Event

The most common — triggers an action.

private void btnSave_Click(object sender, EventArgs e)


{
[Link]("Data saved successfully!");
}

What is a CheckBox?
A CheckBox is a GUI control that allows the user to select or deselect an option — typically
representing a Boolean value (true / false).

Namespace:

[Link]

Common Properties of a CheckBox


Property Description Example

Name Control name used in code. chkSubscribe

[Link] = "Subscribe to
Text The label displayed beside the box. Newsletter";

Indicates whether the box is


Checked [Link] = true;
checked (true/false).

Alignment of the check mark


[Link] =
CheckAlign relative to text (MiddleLeft,
[Link];
MiddleRight).

[Link] =
TextAlign Alignment of the text. [Link];

Allows a third “indeterminate”


ThreeState [Link] = true;
state (null).

Determines if the user can toggle


AutoCheck [Link] = true;
automatically.
Property Description Example

Can appear as a normal box or a


[Link] =
Appearance toggle-style button (Normal, [Link];
Button).

[Link] =
BackColor Background color. [Link];

ForeColor Text color. [Link] = [Link];

[Link] = new Font("Segoe UI",


Font Font style of the text.
10, [Link]);

Enabled Enables or disables interaction. [Link] = false;

Visible Shows or hides the CheckBox. [Link] = true;

Common Events of a CheckBox


Event Description Example Usage

Enable/disable another control


CheckedChanged Occurs when the Checked value changes.
based on selection.

Occurs when the CheckState (Checked, Used with ThreeState =


CheckStateChanged
Unchecked, Indeterminate) changes. true.

Click Triggered when the CheckBox is clicked. Manual handling of toggle.

Enter / Leave When CheckBox gains or loses focus. Change appearance.

MouseEnter /
When mouse pointer enters or leaves. Highlight on hover.
MouseLeave

Example: Basic CheckBox Usage


Example 1 — Simple “Subscribe” Checkbox
private void chkSubscribe_CheckedChanged(object sender, EventArgs e)
{
if ([Link])
[Link]("Thank you for subscribing!");
else
[Link]("You have unsubscribed.");
}
Example 2 — Enable a Button Only if Checked
private void chkAgree_CheckedChanged(object sender, EventArgs e)
{
[Link] = [Link];
}

What is a RadioButton?
A RadioButton is similar to a CheckBox — it allows users to make a choice — but
RadioButtons work in groups, allowing only one option to be selected at a time.

Namespace:

[Link]

When RadioButtons are placed inside the same container (like a GroupBox or Panel), only
one can be selected at a time within that group.

Common Properties of RadioButton


Property Description Example

Name Control name used in code. rdoMale

Text Label shown next to the button. [Link] = "Male";

Checked Indicates if the button is selected. [Link] = true;

Determines if selection changes


AutoCheck [Link] = true;
automatically.

Can display as standard circle or as


[Link] =
Appearance a toggle-style button (Normal,
[Link];
Button).

Sets where the check mark [Link] =


CheckAlign
appears relative to the text. [Link];

Aligns text relative to the check [Link] =


TextAlign
mark. [Link];

Enabled Enables or disables interaction. [Link] = false;

Visible Shows or hides the control. [Link] = true;

BackColor Background color. [Link] = [Link];


Property Description Example

ForeColor Text color. [Link] = [Link];

[Link] = new Font("Segoe UI",


Font Font used for the text. 10, [Link]);

Common Events of RadioButton


Event Description Example Usage

Fires when the Checked state Detect which RadioButton is


CheckedChanged
changes. selected.

Click Fires when the control is clicked. Manual handling of toggle.

Enter / Leave When control gains or loses focus. Highlight background.

MouseEnter /
When mouse enters or leaves. Change appearance on hover.
MouseLeave

Example: Basic RadioButton Usage


Example 1 — Gender Selection
private void rdoMale_CheckedChanged(object sender, EventArgs e)
{
if ([Link])
[Link]("You selected: Male");
}

private void rdoFemale_CheckedChanged(object sender, EventArgs e)


{
if ([Link])
[Link]("You selected: Female");
}

What is a ListBox?
A ListBox displays a list of items from which a user can select one or multiple items.
It’s often used for selections such as categories, items, or database records.

Namespace:

[Link]
Common Properties of ListBox
Property Description Example

Name Control name used in code. lstCities

Collection of items in the


Items [Link]("New York");
ListBox.

Index of the selected item


SelectedIndex int i = [Link];
(starts from 0).

The currently selected item string city =


SelectedItem [Link]();
(object).

The value from a data- string value =


SelectedValue
bound list. [Link]();

Determines if user can


select one or multiple items [Link] =
SelectionMode [Link];
(One, MultiSimple,
MultiExtended).

Automatically sorts items


Sorted [Link] = true;
alphabetically.

Displays items in multiple


MultiColumn [Link] = true;
columns.

Adds a horizontal scrollbar if


HorizontalScrollbar [Link] = true;
items are wide.

Binds the ListBox to a data


DataSource [Link] = cityList;
source (table, list, etc.).

Specifies which column to


DisplayMember display when bound to a [Link] = "CityName";
data source.

Specifies which column


ValueMember value to return when [Link] = "CityID";
selected.

BackColor /
Background and text color. [Link] = [Link];
ForeColor
Property Description Example

[Link] = new Font("Segoe UI",


Font Font of list items.
10);

Controls interactivity and


Enabled / Visible [Link] = true;
visibility.

Common Events of ListBox


Event Description Example Usage

Fires when a different item is Display details about the selected


SelectedIndexChanged
selected. item.

Fires when an item is double-


DoubleClick Open details or edit screen.
clicked.

Click Fires when any item is clicked. Handle simple clicks.

MouseEnter / When mouse enters or leaves


Highlight border, etc.
MouseLeave ListBox.

Delete selected item with Delete


KeyDown / KeyUp Detect key navigation or shortcuts.
key.

Example: Simple ListBox Usage


Example 1 — Add Items and Show Selection
private void Form1_Load(object sender, EventArgs e)
{
[Link]("New York");
[Link]("London");
[Link]("Tokyo");
[Link]("Paris");
}

private void lstCities_SelectedIndexChanged(object sender, EventArgs e)


{
if ([Link] != null)
[Link]("You selected: " +
[Link]());
}
Example 2 — Adding and Removing Items with Buttons
private void btnAdd_Click(object sender, EventArgs e)
{
[Link]([Link]);
[Link]();
}

private void btnRemove_Click(object sender, EventArgs e)


{
if ([Link] != null)
[Link]([Link]);
}

What is a ComboBox?
A ComboBox lets the user:

 Select an item from a drop-down list, or


 Type their own value (if allowed).

Namespace:

[Link]

Common Properties of ComboBox


Property Description Example

Name Control name used in code. cmbCountry

Items Collection of items in the list. [Link]("USA");

Text currently displayed in the


Text [Link] = "Canada";
box.

Index of the selected item (starts


SelectedIndex int i = [Link];
from 0).

string country =
SelectedItem The currently selected item. [Link](
);

string id =
The value from a data-bound
SelectedValue [Link]
ComboBox. ();

DropDownStyle Determines whether user can


Property Description Example

type text. Options:

[Link]
DropDown,
=
DropDownList,
[Link]
Simple. t;

Helps users by auto-suggesting


AutoCompleteMod [Link] =
entries (None, Suggest, [Link];
e
Append, SuggestAppend).

AutoCompleteSour Source for auto-complete [Link] =


ce suggestions. [Link];

DataSource Binds to a list, array, or table. [Link] = dt;

Column to display from data [Link] =


DisplayMember
source. "CountryName";

Column value returned when [Link] =


ValueMember
item is selected. "CountryID";

MaxDropDownIte Number of visible items in the list


[Link] = 10;
ms before scrolling.

Sorted Sorts the items automatically. [Link] = true;

Enabled / Visible Enables or hides the control. [Link] = true;

Common Events of ComboBox


Event Description Example Usage

Fires when the user selects a different


SelectedIndexChanged Load data based on selection.
item.

TextChanged Fires when the text inside changes. Validate custom input.

DropDown Fires when the list is opened. Load data dynamically.

DropDownClosed Fires when the list is closed. Save last selection.


Event Description Example Usage

Click Fires when ComboBox is clicked. Log interaction.

Restrict input or handle


KeyDown / KeyPress Detect keystrokes while focused.
shortcuts.

Example: Basic ComboBox Usage


Example 1 — Add Items Manually
private void Form1_Load(object sender, EventArgs e)
{
[Link]("USA");
[Link]("UK");
[Link]("Canada");
[Link]("Japan");
}

private void cmbCountry_SelectedIndexChanged(object sender, EventArgs e)


{
if ([Link] != null)
[Link]("You selected: " +
[Link]());
}

Example 2 — Auto-Complete Feature


private void Form1_Load(object sender, EventArgs e)
{
[Link] = [Link];
[Link] = [Link];

[Link](new string[] { "USA", "UK", "Canada",


"Australia", "India" });
}

What is a GridView / DataGridView?


The DataGridView control displays data in a tabular (grid) format. Users can view, edit,
delete, or add data. It is widely used for database applications.

Namespace:

[Link]

It supports:

 Column and row customization


 Sorting
 Selection modes
 Data binding (DataTable, List, Database)
Common Properties of DataGridView
Property Description Example

Control name used


Name dgvUsers
in code.

Binds the grid to a


data source
DataSource [Link] = dt;
(DataTable, List,
etc.).

Collection of
Columns columns in the [Link][0].HeaderText = "ID";
grid.

Collection of rows
Rows [Link]("1", "John");
in the grid.

Allow users to add


AllowUserToAddRows [Link] = false;
new rows.

Allow users to
AllowUserToDeleteRows [Link] = true;
delete rows.

Make grid read-


ReadOnly [Link] = true;
only.

Controls
row/column/cell
selection [Link] =
SelectionMode
(FullRowSelect, [Link];
CellSelect,
etc.).

Automatically
[Link] =
AutoSizeColumnsMode adjust column [Link];
width.

Show/hide row
RowHeadersVisible [Link] = false;
header.

ColumnHeadersVisible [Link] = true;


Show/hide column
Property Description Example

header.

Allow multiple row


MultiSelect [Link] = false;
selection.

Background and
BackColor / ForeColor [Link] = [Link];
text colors.

Font for rows and [Link] = new Font("Segoe UI",


Font 10);
headers.

Common Events of DataGridView


Event Description Example Usage

CellClick Fires when a cell is clicked. Select a row to edit.

Fires when content in a cell (like a


CellContentClick Handle button clicks in cells.
button) is clicked.

CellValueChanged Fires when a cell’s value changes. Validate data entry.

RowHeaderMouseClick Fires when row header is clicked. Select entire row.

Update other controls based on


SelectionChanged Fires when selection changes.
selection.

DataError Fires when data binding error occurs. Handle invalid input gracefully.

Example: Populate DataGridView Manually


private void Form1_Load(object sender, EventArgs e)
{
[Link] = 3;
[Link][0].Name = "ID";
[Link][1].Name = "Name";
[Link][2].Name = "Email";

string[] row1 = new string[] { "1", "John Doe", "john@[Link]" };


string[] row2 = new string[] { "2", "Jane Smith", "jane@[Link]" };

[Link](row1);
[Link](row2);

[Link] = [Link];
[Link] = false;
}

Example: Bind DataGridView to Database


Assume a Users table:

CREATE TABLE Users (


UserID INT PRIMARY KEY,
UserName NVARCHAR(50),
Email NVARCHAR(50)
);

C# Code
private void LoadData()
{
using (SqlConnection con = new SqlConnection(connectionString))
{
string query = "SELECT UserID, UserName, Email FROM Users";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
[Link](dt);

[Link] = dt;
[Link] =
[Link];
[Link] = [Link];
}
}

What is a DateTimePicker?
The DateTimePicker allows users to select a date and/or time from a drop-down calendar
or a time spinner.

Namespace:

[Link]

It’s often used for:

 Birthdates
 Appointment scheduling
 Filtering data by date
Common Properties of DateTimePicker
Property Description Example

Control name used in


Name dtpDOB
code.

Gets or sets the selected


Value DateTime dob = [Link];
date/time.

Determines the display


[Link] =
Format format: Long, Short, [Link];
Time, Custom.

Used with Format =


[Link] =
CustomFormat Custom to define a
"dd/MM/yyyy HH:mm";
custom format.

Minimum selectable [Link] = new


MinDate DateTime(2000,1,1);
date.

Maximum selectable [Link] =


MaxDate [Link];
date.

Shows a time-style
ShowUpDown up/down control instead [Link] = true;
of a calendar.

Enable or hide the


Enabled / Visible [Link] = true;
control.

Indicates if the checkbox


Checked if([Link]) {...}
(if shown) is checked.

Adds a checkbox to
ShowCheckBox enable/disable date [Link] = true;
selection.

CalendarMonthBackground / Colors for the drop- [Link] =


CalendarForeColor down calendar. [Link];
Common Events of DateTimePicker
Event Description Example Usage

Fires when the user changes the Update another control or calculate
ValueChanged
date/time. age.

Fires when the drop-down calendar


CloseUp Validate selected date.
closes.

Perform actions before date


DropDown Fires when the calendar is opened.
selection.

KeyDown / Restrict input or implement


Detect keystrokes.
KeyPress shortcuts.

Example: Basic Usage


Example 1 — Display Selected Date
private void dtpDOB_ValueChanged(object sender, EventArgs e)
{
[Link]("Selected Date: " + [Link]());
}

Example 2 — Custom Date Format


private void Form1_Load(object sender, EventArgs e)
{
[Link] = [Link];
[Link] = "dd/MM/yyyy";
[Link] = new DateTime(1950, 1, 1);
[Link] = [Link];}

common properties, methods and events

Common Properties (All Controls)


Property Description Example
Name Name of the control used in code txtName, btnSubmit
Text displayed (or input) in the [Link] = "Hello";
Text
control
Enabled Whether the control is enabled [Link] = false;
Visible Whether the control is visible [Link] = true;
[Link] =
BackColor / Background / Text color [Link];
Property Description Example
ForeColor
[Link] = new Font("Segoe
Font Font of text UI", 10);
Docking style (Top, Bottom, [Link] =
Dock [Link];
Fill)
Anchor Anchoring to form edges `[Link] = [Link]
Order of focus when Tab is [Link] = 0;
TabIndex
pressed
Whether the control can receive [Link] = true;
TabStop
focus via Tab
[Link] =
Cursor Cursor shape when hovering [Link];
Tag Store additional data [Link] = "SaveButton";

Common Methods
Method Description Example
Focus() Sets focus on the control [Link]();
Clear() Clears content (TextBox, ListBox) [Link]();
SelectAll() Selects all text in TextBox [Link]();
Refresh() Redraws the control [Link]();
Show() / Hide() Shows or hides the control [Link](); [Link]();
ResetText() Resets the Text property [Link]();
Invalidate() Forces control to repaint [Link]();

Note: Specific controls have specialized methods, e.g.:

 ComboBox → [Link](), [Link](), [Link]()


 ListBox → [Link](), [Link]()
 DataGridView → [Link](), [Link]()

Common Events
Event Description Example
Fires when the [Link] += btnSubmit_Click;
Click
control is clicked
[Link] +=
DoubleClick Fires on double-click txtName_DoubleClick;
[Link] +=
TextChanged Fires when text txtName_TextChanged;
Event Description Example
changes (TextBox,
ComboBox)
Fires when control [Link] += txtName_Enter;
Enter
receives focus
Fires when control [Link] += txtName_Leave;
Leave
loses focus
KeyPress / KeyDown / Fires on keyboard [Link] +=
KeyUp input txtName_KeyPress;

MouseEnter / Fires when mouse [Link] +=


MouseLeave enters/leaves control btnSubmit_MouseEnter;

Fires for CheckBox / [Link] +=


CheckedChanged chkAgree_CheckedChanged;
RadioButton
Fires for ListBox /
[Link] +=
SelectedIndexChanged ComboBox when cmbCountry_SelectedIndexChanged;
selection changes
CellClick / Fires for [Link] +=
CellValueChanged DataGridView dgvUsers_CellClick;

Fires for [Link] +=


ValueChanged dtpDOB_ValueChanged;
DateTimePicker
DropDown / [Link] +=
Fires for ComboBox cmbCountry_DropDown;
DropDownClosed

What is a ContextMenuStrip?
A ContextMenuStrip is a menu that appears when the user right-clicks on a control or form.
It is often used for shortcut actions specific to that control.

 Namespace:

[Link]

 Components:
o ToolStripMenuItem → Individual menu items
o ToolStripSeparator → Divider between menu items
 Can be assigned to any control via the ContextMenuStrip property.

Common Properties
Property Description Example
Name of the contextMenuFile
Name
ContextMenuStrip
Items Collection of menu items [Link](cutItem);
Property Description Example
Enable or disable the [Link] = true;
Enabled
menu
Visible Show or hide the menu [Link] = true;
Display image margin [Link] = true;
ShowImageMargin
beside items
Display checkboxes [Link] = true;
ShowCheckMargin
beside items
[Link] =
RightToLeft Layout direction [Link];

Common Methods
Method Description Example
Programmatically shows [Link](this, new
Show() Point(50, 50));
the menu at a location
Hide() Hides the menu [Link]();
Dispose() Frees resources [Link]();
[Link]() / Add or remove menu [Link](pasteItem);
[Link]() items

Common Events
Event Description Example
Fires before the menu opens (can be
[Link] +=
Opening used to enable/disable items contextMenu_Opening;
dynamically)
[Link] +=
Opened Fires after the menu is displayed contextMenu_Opened;
[Link] +=
Closing Fires before the menu closes contextMenu_Closing;
[Link] +=
Closed Fires after the menu closes contextMenu_Closed;
[Link] +=
ItemClicked Fires when a menu item is clicked contextMenu_ItemClicked;

Example: Basic Context Menu


private void Form1_Load(object sender, EventArgs e)
{
// Create ContextMenuStrip
ContextMenuStrip contextMenu = new ContextMenuStrip();
// Create menu items
ToolStripMenuItem cutItem = new ToolStripMenuItem("Cut");
ToolStripMenuItem copyItem = new ToolStripMenuItem("Copy");
ToolStripMenuItem pasteItem = new ToolStripMenuItem("Paste");

// Add Click events


[Link] += (s, ev) => { [Link](); };
[Link] += (s, ev) => { [Link](); };
[Link] += (s, ev) => { [Link](); };

// Add items to context menu


[Link](new ToolStripItem[] { cutItem, copyItem,
pasteItem });

// Assign to TextBox
[Link] = contextMenu;
}

What is a MenuStrip?
A MenuStrip is a control that provides a main menu for a form, typically appearing at the
top of the window, like File, Edit, View menus in most applications.

 Namespace:

[Link]

 Composed of:
o ToolStripMenuItem → Individual menu items
o DropDownItems → Submenus under a menu item

Common Properties
Property Description Example
Name of the MenuStrip menuStrip1
Name
control
Collection of top-level menu [Link](fileMenuItem);
Items
items
Dock Docking style (usually Top) [Link] = [Link];
Visible Show or hide the menu strip [Link] = true;
Enable or disable the menu [Link] = true;
Enabled
strip
Determines drawing style
[Link] =
RenderMode (System, Professional, [Link];
ManagerRenderMode)
[Link] =
RightToLeft Layout direction [Link];
If the menu stretches across [Link] = true;
Stretch
the form
Common Methods
Method Description Example
[Link]() / Add or remove top-level [Link](editMenu);
[Link]() menu items
[Link]() Remove all items [Link]();
Updates the layout after [Link]();
PerformLayout()
changes
Dispose() Frees resources [Link]();

Common Events
Event Description Example
Fires when any menu item [Link] +=
ItemClicked menuStrip1_ItemClicked;
is clicked
MenuActivate / Fires when menu is [Link] += ...;
MenuDeactivate activated/deactivated
MouseEnter / Fires when mouse enters or [Link] += ...;
MouseLeave leaves menu

Note: Each ToolStripMenuItem also has its own events like Click, DropDownOpening,
DropDownClosed, CheckedChanged.

Example: Basic MenuStrip with File and Edit


private void Form1_Load(object sender, EventArgs e)
{
// Create MenuStrip
MenuStrip menuStrip1 = new MenuStrip();

// File menu
ToolStripMenuItem fileMenu = new ToolStripMenuItem("File");
ToolStripMenuItem newItem = new ToolStripMenuItem("New");
ToolStripMenuItem openItem = new ToolStripMenuItem("Open");
ToolStripMenuItem exitItem = new ToolStripMenuItem("Exit");
[Link] += (s, ev) => { [Link](); };

[Link](new ToolStripItem[] { newItem,


openItem, exitItem });

// Edit menu
ToolStripMenuItem editMenu = new ToolStripMenuItem("Edit");
ToolStripMenuItem cutItem = new ToolStripMenuItem("Cut");
ToolStripMenuItem copyItem = new ToolStripMenuItem("Copy");
ToolStripMenuItem pasteItem = new ToolStripMenuItem("Paste");
[Link](new ToolStripItem[] { cutItem,
copyItem, pasteItem });

// Add top-level menus to MenuStrip


[Link](new ToolStripItem[] { fileMenu, editMenu });

// Add MenuStrip to form


[Link] = menuStrip1;
[Link](menuStrip1);
}

What is GDI?
GDI (Graphics Device Interface) is a Windows API for representing graphical objects and
transmitting them to output devices such as monitors, printers, and screens.

 Purpose: Draw shapes, text, images, and handle graphical output.


 Managed in .NET through the [Link] namespace.
 Graphics object is central for drawing in Windows Forms.

Key Classes in [Link]


Class Purpose
Graphics Represents a drawing surface; used to draw shapes, text, images.
Pen Defines the color, width, and style of a line or border.
Fills shapes with colors, gradients, or patterns. Common types:
Brush
SolidBrush, LinearGradientBrush, TextureBrush.
Font Defines the font used to draw text.
Color Represents colors (RGB, ARGB).
Image / Bitmap Represents images for drawing or manipulation.
Rectangle /
Represents rectangular areas.
RectangleF
Point / PointF Represents coordinates on the drawing surface.

Graphics Object
 Obtained from PaintEventArgs in a control’s Paint event:

private void Form1_Paint(object sender, PaintEventArgs e)


{
Graphics g = [Link]; // Obtain the Graphics object
}

 Or from a control:
Graphics g = [Link]();

Tip: Using Paint event is preferred to prevent losing drawings when the window refreshes.

Common Graphics Methods


Method Description Example
DrawLine(Pen, x1, y1, Draw a [Link]([Link], 10, 10, 100, 100);
x2, y2) straight line
DrawRectangle(Pen, x, Draw a [Link]([Link], 50, 50, 100,
y, width, height) rectangle 50);

FillRectangle(Brush, x, Fill a [Link]([Link], 50, 50, 100,


y, width, height) rectangle 50);

DrawEllipse(Pen, x, y, Draw an [Link]([Link], 50, 50, 100,


width, height) ellipse 50);

FillEllipse(Brush, x, y, [Link]([Link], 50, 50, 100,


Fill an ellipse 50);
width, height)
DrawString(string, [Link]("Hello", new Font("Arial",
Draw text 12), [Link], 50, 50);
Font, Brush, x, y)
DrawImage(Image, x, [Link]([Link]("[Link]"),
Draw image 10, 10);
y)
Clear surface [Link]([Link]);
Clear(Color)
with a color

What is SDI?
SDI (Single Document Interface) is a type of GUI application where the application
handles only one document or window at a time.

 Example: Notepad, Paint.


 Contrast with MDI (Multiple Document Interface), where a single parent window
can host multiple child documents (e.g., Excel, Visual Studio).
 In SDI, every window is independent; opening another document usually opens a new
instance of the application.

Features of SDI
Feature Description
Single Window Only one document or form is active at a time.
Independent
Each document runs in its own window/process.
Windows
Simpler Design Easier to implement than MDI.
Feature Description
Unlike MDI, SDI doesn’t manage multiple child windows inside a
No Child Forms
parent.

SDI in Windows Forms


 Form represents the window/document.
 A typical SDI application has:
o MenuStrip or ToolStrip for commands
o StatusStrip for status information
o Single Form instance handling the document or data

Example scenario: Notepad clone:

 Only one file can be open at a time.


 New instance of the application opens another file (not inside the same window).

Basic SDI Implementation in C# Windows Forms


public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void newToolStripMenuItem_Click(object sender, EventArgs e)


{
// Close current document and create a new one
[Link]();
Form1 newForm = new Form1();
[Link]();
}

private void openToolStripMenuItem_Click(object sender, EventArgs e)


{
OpenFileDialog openFile = new OpenFileDialog();
if ([Link]() == [Link])
{
string content = [Link]([Link]);
[Link] = content; // Assuming a TextBox for content
}
}
}

Advantages of SDI
 Simple and easy to implement.
 Less memory usage than MDI because each document runs independently.
 User interface is straightforward and easy to understand.
Disadvantages of SDI
 Managing multiple documents is cumbersome; users need multiple windows.
 Harder to compare or work across multiple documents simultaneously.
 No built-in parent-child management like MDI.

What is MDI?
MDI (Multiple Document Interface) is a type of GUI application where a single parent
window can host multiple child windows (documents) inside it.

 Example: Microsoft Excel, Visual Studio.


 Allows users to work on multiple documents simultaneously within the same
application window.
 Provides a centralized parent form that manages child forms.

Features of MDI
Feature Description
Parent Form (MDI
Main window that holds multiple child windows.
Container)
Child Forms Individual documents/windows inside the parent.
Menu Integration Menu items can be merged between parent and child forms.
Child windows can be minimized, maximized, cascaded, or
Window Management
tiled.
Single Instance Only one instance of parent form; multiple children allowed.

MDI in Windows Forms


 Set the IsMdiContainer property of the parent form to true.
 Create child forms and set their MdiParent property to the parent form.
 Example uses MenuStrip to create and open new child documents.

Basic MDI Implementation in C#


// Parent Form
public partial class ParentForm : Form
{
public ParentForm()
{
InitializeComponent();
[Link] = true; // Set as MDI container
}
private void newChildToolStripMenuItem_Click(object sender, EventArgs e)
{
ChildForm child = new ChildForm();
[Link] = this; // Assign parent
[Link] = "Document " + [Link]; // Optional
[Link]();
}

private void cascadeToolStripMenuItem_Click(object sender, EventArgs e)


{
[Link]([Link]);
}

private void tileHorizontalToolStripMenuItem_Click(object sender,


EventArgs e)
{
[Link]([Link]);
}

private void tileVerticalToolStripMenuItem_Click(object sender,


EventArgs e)
{
[Link]([Link]);
}
}

// Child Form
public partial class ChildForm : Form
{
public ChildForm()
{
InitializeComponent();
}
}

Advantages of MDI
 Can manage multiple documents inside a single parent.
 Easier for users to switch and organize multiple documents.
 Centralized control for menus, toolbar, and status bar.
 Supports cascading or tiling child windows.

Disadvantages of MDI
 More complex to implement than SDI.
 Can become confusing if too many child windows are open.
 Requires careful menu and window management

What is a Dialog Box?


A dialog box is a small window that prompts the user to make a decision, enter information,
or display messages.

 Usually modal (blocks other windows until closed) or modeless (doesn’t block other
windows).
 Common in SDI and MDI applications.

Types of dialog boxes:

1. MessageBox – Display information, warnings, or errors.


2. OpenFileDialog / SaveFileDialog – Open or save files.
3. FolderBrowserDialog – Select folders.
4. Custom Form Dialog – User-defined forms used as dialogs.

Properties of Dialog Boxes


Property Description

Text Title of the dialog box

DialogResult Result returned by the dialog (OK, Cancel, Yes, No)

FileName Used in OpenFileDialog/SaveFileDialog to get selected file

Filter File types displayed in Open/Save dialogs

InitialDirectory Default folder path in file dialogs

Multiselect Allows selecting multiple files (OpenFileDialog)

SelectedPath Selected folder path (FolderBrowserDialog)

Common Methods
Method Description

ShowDialog() Opens the dialog box modally

Show() Opens the dialog box modelessly (for custom forms)

Reset() Resets properties to default (for file/folder dialogs)

Common Events
Event Description

FileOk Fires before a file dialog closes (used to validate selection)

HelpRequest Fires when the user clicks the Help button (if enabled)

Examples
5.1 MessageBox
DialogResult result = [Link](
"Do you want to save changes?",
"Save File",
[Link],
[Link]
);

if (result == [Link])
{
// Save the file
}
else if (result == [Link])
{
// Discard changes
}
[Link] & Database
[Link]
 [Link] (ActiveX Data Object for .NET) is an object-oriented set of libraries that allows you to
interact with data sources.
 Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet, or an
XML file.
 It is a part of the base class library that is included with the Microsoft .NET Framework.
 It is commonly used by programmers to access and modify data stored in relational database
systems, though it can also access data in non- relational sources.

Data providers:
 The Data providers are extensible. Developers can create their own providers for a proprietary data
source.
 There are some examples of data providers such as SQL Server providers, OLE DB and Oracle
provider.
 [Link] allows us to interact with different types of data sources and different types of
databases. However, there isn't a single set of classes that allow you to accomplish this universally.
 Since different data sources expose different protocols, there are more data sources every day that
allow you to communicate with them directly through .NET [Link] class libraries.
 These libraries are called Data Providers and are usually named for the protocol or data source type
they allow you to interact with.

 [Link] provides the following two types of classes objects:


o Connection-based: They are the data provider objects such as Connection, Command,
DataAdapter and DataReader. They execute SQL statements and connect to a database.
o Content-based: They are found in the [Link] namespace and includes DataSet,
DataColumn, DataRow and DataRelation. They are completely independent of the type of
data source.
 [Link] Namespaces

Data Provider:
Connection Object:
 Each data provider in [Link] contains a Connection class that inherits from the
[Link] class.
 The DbConnection serves as the base class for all the Connection classes of different data
providers.

 To interact with a database, you must have a connection to it. The connection helps identify the
database server, the database name, user name, password, and other parameters that are required
for connecting to the data base.

Creating a SqlConnection Object:

 A SqlConnection is an object, just like any other C# object. Most of the time, you just declare and
instantiate the SqlConnection all at the same time, as shown below:
 SqlConnection conn = new SqlConnection( "Data Source=(local);Initial
Catalog=Northwind;Integrated Security=true");
 The SqlConnection object instantiated above uses a constructor with a single argument of type
string This argument is called a connection string.
Using a SqlConnection:
 The purpose of creating a SqlConnection object is so you can enable other [Link] code to work
with a database.
 Other [Link] objects, such as a SqlCommand and a SqlDataAdapter take a connection object
as a parameter. The sequence of operations occurring in the lifetime of a SqlConnection are as
follows:
 Instantiate the SqlConnection.
 Open the connection.
 Pass the connection to other [Link] objects.
 Perform database operations with the other [Link] objects.
 Close the connection.

Command:
 Each data provider has their Command class which is use to execute SQL commands or stored
procedures to the database.
 Each Command class inherits from the [Link] base class.
 The following are the different flavors of the Command class for each data provider.

 SqlCommand object allows you to specify what type of interaction you want to perform with a
database.
 SqlCommand object can be used to support disconnected architecture.
 For example, you can do select, insert, modify, and delete commands on rows of data in a database
table.
 Creating a SqlCommand Object
 Similar to other C# objects, you instantiate a SqlCommand object via the new instance declaration,
as follows:
 SqlCommand cmd = new SqlCommand ("select CategoryName from Categories", conn);
 For instantiating a SqlCommand object. It takes a string parameter that holds the command you
want to execute and a reference to a SqlConnection object.
 The following are important built in methods uses in the Command Object to execute the SQL
statements.
Data Reader
 DataReader object allows forward-only, read-only access to a database.
 Using DataReader is the connected way of accessing data and an open connection must be
available first.
 Each provider has its own version of DataReader which inherits to the
[Link] base class.
 DataReader cannot be created directly from code, they can created only by calling the
ExecuteReader method of a Command Object.
 SqlDataReader sqlReader = [Link]();
 Connection Object can contain only one DataReader at a time and the connection in the
DataReader remains open, also it cannot be used for any other purpose while data is being
accessed.
 Read() method in the DataReader is used to read the rows from DataReader and it always moves
forward to a new valid row, if any row exist .
 [Link]();

Data Adapter
 DataAdapter can be considered as a bridge between the actual data source to your application.
 It is commonly used together with a DataSet. Using DataAdapter and DataSet is the disconnected
way of retrieving data from the data source.
 DataAdapter allows you to fill a DataSet with values from the data source, or execute different
commands to the data source.
 DataAdapter class inherits from the [Link] base class.
 Each data provider has its own version of DataAdapter.

Data Adapter Properties:

 The DataAdapter is the one that actually executes the commands to data source. It has a
SelectCommandproperty which accepts a DbCommand object that specifies the SELECT statement
used to retrieved data from the data source.
 The following shows you an example of assigning a SelectCommand.
 SqlCommand selectCommand = new SqlCommand("SELECT * FROM Students", connection);
 SqlDataAdapter adapter = new SqlDataAdapter();
 [Link] = selectCommand;
 To execute the command specified by the SelectCommand property, we can use the Fill() method
of the DbDataAdapter class.
 The Fill() method requires an instance of the DataSet or DataTable classes.
 The following shows an example of filling a DataTable instance with values retrieved from the
database.
 [Link]( DataSet/DataTable);

Dataset
 [Link] class holds data that are retrieved from the database.
 DataSet class allows you to hold disconnected data.
 DataSet contains DataTableCollection and theirDataRelationCollection . It represents a complete
set of data including the tables that contain, order, and constrain the data, as well as the
relationships between the tables.
 Dataset contains more than one Table at a time. We can set up Data Relations between these tables
within the DataSet. The data set may comprise data for one or more members, corresponding to the
number of rows.
 DataAdapter Object allows us to populate DataTables in a DataSet. We can use Fill method of the
DataAdapter for populating data in a Dataset. The DataSet can be filled either from a data source or
dynamically.

Data Table

 In [Link], DataTable objects are used to represent the tables in a DataSet.


 DataTable represents one table of in-memory relational data; the data is local to the .NET-based
application in which it resides,
 DataTable is a relational database like table in the memory.
 It has a structural definition and constraints like unique constraints.
 We can create hierarchical relationships among many DataTables dynamically in a DataSet.
 To create DataTable,

 DataTable myDataTable = new DataTable(“Sample_Table”);


 DataColumn
 Stored in collection named columns and represents the schema of a column in a DataTable.
 DataRow
 DataRow represents a row of data in a DataTable.
 You can add data to the table using DataRow Object.
 DataRowCollection object represents a collection of data rows of a table.
 Use DataTable’s NewRow metgod to return a DataRow object of data table,Add values to the data
row and add a row to the data table.

 DataTable myDataTable = new DataTable(“Sample_Table”); DataColumn myDataColumn new


DataColumn();
 DataRow my DataRow = [Link]();

Data View
 DataView provides different views of the data stored in a DataTable.
 That is we can customize the views of data from a DataTable.
 DataView can be used to sort, filter, and search the data in
 a DataTable , additionally we can add new rows and modify the content in a DataTable.
 We can create DataView in two different ways. We can use theDataView Constructor , or you can
create a reference to the DefaultView Property of the DataTable.
 The DataView constructor can be empty, or it can take either a DataTable as a single argument, or
a DataTable along with filter criteria, sort criteria, and a row state filter.

 dv = new DataView(dt, “Filter“,”Sort”, [Link]);

 dv = [Link];

Data GridView

 DataGridView control is designed to be a complete solution for displaying tabular data with
Windows Forms.
 DataGridView control is highly configurable and extensible, and it provides many properties,
methods, and events to customize its appearance and behavior.
 DataGridView control makes it easy to define the basic appearance of cells and the display
formatting of cell values.
 The cell is the fundamental unit of interaction for the DataGridView.
 All cells derive from the DataGridViewCell base class. Each cell within the DataGridView control
can have its own style, such as text format, background color, foreground color, and font.
Typically, however, multiple cells will share particular style characteristics.
 The data type for the cell's Value property by default is of type Object.
 Using Data GridView
 Find DataGridView control from ToolBox under Data Tab.

 You can bind data into DataGridView in twop different ways:


 Using DataGridView Configuration Wizard
 Dynamically by C# CODE
 Using DataGridView Configuration Wizard

Click on the DataSource property of DataGridView Control and click on Add Project DataSource

 You will get DataGridView Config Wizard Dialogbox.


 Select Database and click Next> button.
Here you can create new database connection or you can select exsiting database connection. After
selecting database conncetion click next.

Then it will ask you to save connection string in application configration file or not.
it will ask to choose database objects like tables/Views and it will make DataSet from chosen database
objects and click finish.
 You can see it will automaticaly add DataSet, DataAdapter and binding source controls into
application.
 You can find following automatic generated code in Form_Load Event
 // TODO: This line of code loads data into the 'db1DataSet.Table1' table. You can move, or remove
it, as needed.
 [Link](this.db1DataSet.Table1);
 Data GridView Programming

 Use DataSource property and bind DataTable or DataSet to it. OleDbConnection con = new
OleDbConnection(@“ConnectionString"); OleDbDataAdapter ad = new
OleDbDataAdapter("Select * from Table1",con);
 DataTable dt = new DataTable(); [Link](dt); [Link] = dt;
[Link]();
CRUD Operation In C# Application

CRUD operation, using C# is the common program for beginner, intermediate and an expert. During
CRUD operation, the programmer is facing different types of errors and it will take lot of time to resolve.

This article shows how to insert, update and delete the records from the database, using C# Server side
code. If the programmer has a basic knowledge of C# and Visual Studio, then he will not face any
difficulty during the program execution.

Here, I am using SQL database to insert, update and delete operation. Before starting, you should add DLL
and afterwards, you should add namespace under it.

Step 1

using [Link];

You should use namespace given above to connect with SQL database.

Step2

You have to declare connection string outside the class.

1. SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog = Sample;Integrated


Security=true;");
2. SqlCommand cmd;
3. SqlDataAdapter da;
4. int ID = 0;

Step 3

Insert data in the database, as sgiven below.

1. if (txt_Name.Text != "" && txt_State.Text != "") {


2. cmd = new SqlCommand("insert into tbl_Record(Name,State) values (@name,@state)", con);
3. [Link]();
4. [Link]("@name", txt_Name.Text);
5. [Link]("@state", txt_State.Text);
6. [Link]();
7. [Link]();
8. [Link]("Record Inserted Successfully");
9. DisplayData();
10. ClearData();
11. } else {
12. [Link]("Please Provide Details!");
13. }
Step 4

Updating record is given below.

1. if (txt_Name.Text != "" && txt_State.Text != "") {


2. cmd = new SqlCommand("update tbl_Record set Name=@name,Sta te=@state where ID=@id",
con);
3. [Link]();
4. [Link]("@id", ID);
5. [Link]("@name", txt_Name.Text);
6. [Link]("@state", txt_State.Text);
7. [Link]();
8. [Link]("Record Updated Successfully");
9. [Link]();
10. DisplayData();
11. ClearData();
12. } else {
13. [Link]("Please Select Record to Update");
14. }

Step 5

Display record is shown below.

1. [Link]();
2. DataTable dt = new DataTable();
3. da = new SqlDataAdapter("select * from tbl_Record", con);
4. [Link](dt);
5. [Link] = dt;
6. [Link]();

Step 6

Proceed, as shown below to delete the record.


1. if (ID != 0) {
2. cmd = new SqlCommand("delete tbl_Record where ID=@id", con);
3. [Link]();
4. [Link]("@id", ID);
5. [Link]();
6. [Link]();
7. [Link]("Record Deleted Successfully!");
8. DisplayData();
9. ClearData();
10. } else {
11. [Link]("Please Select Record to Delete");
12. }
13. }

At last, I have called clear method to clear all the textboxes.


1. txt_Name.Text = "";
2. txt_State.Text = "";
3. ID = 0;

You might also like