Windows Forms GUI and Database Basics
Windows Forms GUI and Database Basics
APPLIED SCIENCES
Notes of Unit-III
A TextBox in Windows Forms is a control that allows users to enter, display, or edit text in
your application.
Namespace:
[Link]
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]
[Link]("[Link]");
[Link] =
TextAlign Alignment of text.
[Link];
KeyDown /
Detect key presses while the button has focus. Trigger on Enter or Space key.
KeyUp
Example: Basic Button Event Handlers
(1) Click Event
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]
[Link] = "Subscribe to
Text The label displayed beside the box. Newsletter";
[Link] =
TextAlign Alignment of the text. [Link];
[Link] =
BackColor Background color. [Link];
MouseEnter /
When mouse pointer enters or leaves. Highlight on hover.
MouseLeave
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.
MouseEnter /
When mouse enters or leaves. Change appearance on hover.
MouseLeave
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
BackColor /
Background and text color. [Link] = [Link];
ForeColor
Property Description Example
What is a ComboBox?
A ComboBox lets the user:
Namespace:
[Link]
string country =
SelectedItem The currently selected item. [Link](
);
string id =
The value from a data-bound
SelectedValue [Link]
ComboBox. ();
[Link]
DropDown,
=
DropDownList,
[Link]
Simple. t;
TextChanged Fires when the text inside changes. Validate custom input.
Namespace:
[Link]
It supports:
Collection of
Columns columns in the [Link][0].HeaderText = "ID";
grid.
Collection of rows
Rows [Link]("1", "John");
in the grid.
Allow users to
AllowUserToDeleteRows [Link] = true;
delete rows.
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.
header.
Background and
BackColor / ForeColor [Link] = [Link];
text colors.
DataError Fires when data binding error occurs. Handle invalid input gracefully.
[Link](row1);
[Link](row2);
[Link] = [Link];
[Link] = false;
}
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]
Birthdates
Appointment scheduling
Filtering data by date
Common Properties of DateTimePicker
Property Description Example
Shows a time-style
ShowUpDown up/down control instead [Link] = true;
of a calendar.
Adds a checkbox to
ShowCheckBox enable/disable date [Link] = true;
selection.
Fires when the user changes the Update another control or calculate
ValueChanged
date/time. age.
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]();
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;
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;
// 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.
// 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](); };
// 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 });
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.
Graphics Object
Obtained from PaintEventArgs in a control’s Paint event:
Or from a control:
Graphics g = [Link]();
Tip: Using Paint event is preferred to prevent losing drawings when the window refreshes.
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.
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.
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.
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.
// 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
Usually modal (blocks other windows until closed) or modeless (doesn’t block other
windows).
Common in SDI and MDI applications.
Common Methods
Method Description
Common Events
Event Description
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.
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.
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.
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
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 = [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.
Click on the DataSource property of DataGridView Control and click on Add Project DataSource
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
Step 3
Step 5
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