0% found this document useful (0 votes)
25 views25 pages

Unit 4

Uploaded by

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

Unit 4

Uploaded by

Hemavathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Power of Application Structure – User Interface Features – Transaction – Forms Events – Custom

Reports – Distributing Application – Table Operations – Data Storage Methods – Storing Data
Columns – Data Clustering and Partitioning.

Forms Events

Let's start with creating a Window Forms Application by following the


following steps in Microsoft Visual Studio - File → New Project → Windows
Forms Applications

Finally, select OK, Microsoft Visual Studio creates your project and displays
following window Form with a name Form1.
Visual Basic Form is the container for all the controls that make up the user
interface. Every window you see in a running visual basic application is a
form, thus the terms form and window describe the same entity. Visual
Studio creates a default form for you when you create a Windows Forms
Application.

Every form will have title bar on which the form's caption is displayed and
there will be buttons to close, maximize and minimize the form shown below

If you click the icon on the top left corner, it opens the control menu, which
contains the various commands to control the form like to move control from
one place to another place, to maximize or minimize the form or to close the
form.

Form Properties
Following table lists down various important properties related to a form.
These properties can be set or read during application execution. You can
refer to Microsoft documentation for a complete list of properties associated
with a Form control −

S.
Properties Description
N

The button that's automatically activated when you press Enter, no


1 AcceptButton matter which control has the focus at the time. Usually the OK
button on a form is set as AcceptButton for a form.

The button that's automatically activated when you hit the Esc key.
2 CancelButton Usually, the Cancel button on a form is set as CancelButton for a
form.

3 AutoScale This Boolean property determines whether the controls you place
on the form are automatically scaled to the height of the current
font. The default value of this property is True. This is a property
of the form, but it affects the controls on the form.

This Boolean property indicates whether scroll bars will be


4 AutoScroll automatically attached to the form if it is resized to a point that not
all its controls are visible.

AutoScrollMinSiz This property lets you specify the minimum size of the form,
5
e before the scroll bars are attached.

AutoScrollPositio The AutoScrollPosition is the number of pixels by which the two


6
n scroll bars were displaced from their initial locations.

7 BackColor Sets the form background color.

The BorderStyle property determines the style of the form's border


and the appearance of the form −
 None − Borderless window that can't be resized.
 Sizable − This is default value and will be used for
resizable window that's used for displaying regular forms.
 Fixed3D − Window with a visible border, "raised"
relative to the main area. In this case, windows can't be
resized.
 FixedDialog − A fixed window, used to create dialog
8 BorderStyle
boxes.
 FixedSingle − A fixed window with a single line
border.
 FixedToolWindow − A fixed window with a Close
button only. It looks like the toolbar displayed by the
drawing and imaging applications.
 SizableToolWindow − Same as the
FixedToolWindow but resizable. In addition, its caption
font is smaller than the usual.

By default, this property is True and you can set it to False to hide
9 ControlBox
the icon and disable the Control menu.

If True, allows the form to respond to mouse and keyboard events;


10 Enabled
if False, disables form.

11 Font This property specify font type, style, size

Determines whether a Help button should be displayed in the


12 HelpButton
caption box of the form.

13 Height This is the height of the Form in pixels.

By default, this property is True and you can set it to False to hide
14 MinimizeBox
the Minimize button on the title bar.

15 MaximizeBox By default, this property is True and you can set it to False to hide
the Maximize button on the title bar.

This specifies the minimum height and width of the window you
16 MinimumSize
can minimize.

This specifies the maximum height and width of the window you
17 MaximumSize
maximize.

18 Name This is the actual name of the form.

This property determines the initial position of the form when it's
first displayed. It will have any of the following values −
 CenterParent − The form is centered in the area of its
parent form.
 CenterScreen − The form is centered on the monitor.
 Manual − The location and size of the form will
19 StartPosition
determine its starting position.
 WindowsDefaultBounds − The form is positioned
at the default location and size determined by Windows.
 WindowsDefaultLocation − The form is
positioned at the Windows default location and has the
dimensions you've set at design time.

20 Text The text, which will appear at the title bar of the form.

These two properties set or return the coordinates of the form's top-
21 Top, Left
left corner in pixels.

This property is a True/False value that lets you specify whether


22 TopMost the form will remain on top of all other forms in your application.
Its default property is False.

23 Width This is the width of the form in pixel.

Form Methods
The following are some of the commonly used methods of the Form class.
You can refer to Microsoft documentation for a complete list of methods
associated with forms control −

Sr.No
Method Name & Description
.

Activate
1
Activates the form and gives it focus.

ActivateMdiChild
2
Activates the MDI child of a form.
AddOwnedForm
3
Adds an owned form to this form.

BringToFront
4
Brings the control to the front of the z-order.

CenterToParent
5
Centers the position of the form within the bounds of the parent form.

CenterToScreen
6
Centers the form on the current screen.

Close
7
Closes the form.

Contains
8
Retrieves a value indicating whether the specified control is a child of the control.

Focus
9
Sets input focus to the control.

Hide
10
Conceals the control from the user.

Refresh
11 Forces the control to invalidate its client area and immediately redraw itself and any child
controls.

Scale(SizeF)
12
Scales the control and all child controls by the specified scaling factor.

ScaleControl
13
Scales the location, size, padding, and margin of a control.

ScaleCore
14
Performs scaling of the form.

Select
15
Activates the control.

SendToBack
16
Sends the control to the back of the z-order.

SetAutoScrollMargin
17
Sets the size of the auto-scroll margins.

SetDesktopBounds
18
Sets the bounds of the form in desktop coordinates.

SetDesktopLocation
19
Sets the location of the form in desktop coordinates.
SetDisplayRectLocation
20
Positions the display window to the specified value.

Show
21
Displays the control to the user.

ShowDialog
22
Shows the form as a modal dialog box.

Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.

Form Events
Following table lists down various important events related to a form. You can
refer to Microsoft documentation for a complete list of events associated with
forms control −

Sr.No
Event Description
.

1 Activated Occurs when the form is activated in code or by the user.

2 Click Occurs when the form is clicked.

3 Closed Occurs before the form is closed.

4 Closing Occurs when the form is closing.

5 DoubleClick Occurs when the form control is double-clicked.

6 DragDrop Occurs when a drag-and-drop operation is completed.

7 Enter Occurs when the form is entered.

8 GotFocus Occurs when the form control receives focus.

HelpButtonClicke
9 Occurs when the Help button is clicked.
d

10 KeyDown Occurs when a key is pressed while the form has focus.

11 KeyPress Occurs when a key is pressed while the form has focus.

12 KeyUp Occurs when a key is released while the form has focus.

13 Load Occurs before a form is displayed for the first time.


14 LostFocus Occurs when the form loses focus.

Occurs when the mouse pointer is over the form and a mouse
15 MouseDown
button is pressed.

16 MouseEnter Occurs when the mouse pointer enters the form.

17 MouseHover Occurs when the mouse pointer rests on the form.

18 MouseLeave Occurs when the mouse pointer leaves the form.

19 MouseMove Occurs when the mouse pointer is moved over the form.

Occurs when the mouse pointer is over the form and a mouse
20 MouseUp
button is released.

Occurs when the mouse wheel moves while the control has
21 MouseWheel
focus.

22 Move Occurs when the form is moved.

23 Resize Occurs when the control is resized.

24 Scroll Occurs when the user or code scrolls through the client area.

25 Shown Occurs whenever the form is first displayed.

26 VisibleChanged Occurs when the Visible property value changes.

Basic Controls
VB.Net provides a huge variety of controls that help you to create rich user
interface. Functionalities of all these controls are defined in the respective
control classes. The control classes are defined in
the System.Windows.Forms namespace.

The following table lists some of the commonly used controls −

Sr.No. Widget & Description

1 Forms
The container for all the controls that make up the user interface.

2 TextBox
It represents a Windows text box control.

3 Label
It represents a standard Windows label.
4 Button
It represents a Windows button control.

5 ListBox
It represents a Windows control to display a list of items.

6 ComboBox
It represents a Windows combo box control.

RadioButton
7 It enables the user to select a single option from a group of choices when paired with other
RadioButton controls.

8 CheckBox
It represents a Windows CheckBox.

9 PictureBox
It represents a Windows picture box control for displaying an image.

10 ProgressBar
It represents a Windows progress bar control.

11 ScrollBar
It Implements the basic functionality of a scroll bar control.

DateTimePicker
12 It represents a Windows control that allows the user to select a date and a time and to
display the date and time with a specified format.

13 TreeView
It displays a hierarchical collection of labeled items, each represented by a TreeNode.

ListView
14 It represents a Windows list view control, which displays a collection of items that can be
displayed using one of four different views.

The following diagram shows the common dialog class inheritance −


All these above-mentioned classes have corresponding controls that could be
added from the Toolbox during design time. You can include relevant
functionality of these classes to your application, either by instantiating the
class programmatically or by using relevant controls.

When you double click any of the dialog controls in the toolbox or drag the
control onto the form, it appears in the Component tray at the bottom of the
Windows Forms Designer, they do not directly show up on the form.

The following table lists the commonly used dialog box controls. Click the
following links to check their detail −

Sr.No
Control & Description
.

ColorDialog
1 It represents a common dialog box that displays available colors along with controls that
enable the user to define custom colors.

FontDialog
2 It prompts the user to choose a font from among those installed on the local computer and
lets the user select the font, font size, and color.

OpenFileDialog
3
It prompts the user to open a file and allows the user to select a file to open.

SaveFileDialog
4 It prompts the user to select a location for saving a file and allows the user to specify the
name of the file to save data.

PrintDialog
5 It lets the user to print documents by selecting a printer and choosing which sections of the
document to print from a Windows Forms application.

VB.Net is an event-driven language. There are mainly two types of events −


 Mouse events
 Keyboard events

Handling Mouse Events


Mouse events occur with mouse movements in forms and controls. Following
are the various mouse events related with a Control class −

 MouseDown − it occurs when a mouse button is pressed


 MouseEnter − it occurs when the mouse pointer enters the control
 MouseHover − it occurs when the mouse pointer hovers over the
control
 MouseLeave − it occurs when the mouse pointer leaves the control
 MouseMove − it occurs when the mouse pointer moves over the
control
 MouseUp − it occurs when the mouse pointer is over the control and
the mouse button is released
 MouseWheel − it occurs when the mouse wheel moves and the
control has focus

Applications communicate with a database, firstly, to retrieve the data stored


there and present it in a user-friendly way, and secondly, to update the
database by inserting, modifying and deleting data.

Microsoft ActiveX Data Objects.Net (ADO.Net) is a model, a part of the .Net


framework that is used by the .Net applications for retrieving, accessing and
updating data.

ADO.Net Object Model


ADO.Net object model is nothing but the structured process flow through
various components. The object model can be pictorially described as −
The data residing in a data store or database is retrieved through the data
provider. Various components of the data provider retrieve data for the
application and update data.

An application accesses data either through a dataset or a data reader.

 Datasets store data in a disconnected cache and the application


retrieves data from it.
 Data readers provide data to the application in a read-only and
forward-only mode.

Data Provider
A data provider is used for connecting to a database, executing commands
and retrieving data, storing it in a dataset, reading the retrieved data and
updating the database.

The data provider in ADO.Net consists of the following four objects −

Sr.No
Objects & Description
.

Connection
1
This component is used to set up a connection with a data source.

Command
2 A command is a SQL statement or a stored procedure used to retrieve, insert, delete or
modify data in a data source.

3 DataReader
Data reader is used to retrieve data from a data source in a read-only and forward-only
mode.

DataAdapter
This is integral to the working of ADO.Net since data is transferred to and from a database
4 through a data adapter. It retrieves data from a database into a dataset and updates the
database. When changes are made to the dataset, the changes in the database are actually
done by the data adapter.

There are following different types of data providers included in ADO.Net

 The .Net Framework data provider for SQL Server - provides access to
Microsoft SQL Server.
 The .Net Framework data provider for OLE DB - provides access to data
sources exposed by using OLE DB.
 The .Net Framework data provider for ODBC - provides access to data
sources exposed by ODBC.
 The .Net Framework data provider for Oracle - provides access to
Oracle data source.
 The EntityClient provider - enables accessing data through Entity Data
Model (EDM) applications.

Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.

DataSet
DataSet is an in-memory representation of data. It is a disconnected, cached
set of records that are retrieved from a database. When a connection is
established with the database, the data adapter creates a dataset and stores
data in it. After the data is retrieved and stored in a dataset, the connection
with the database is closed. This is called the 'disconnected architecture'. The
dataset works as a virtual database containing tables, rows, and columns.

The following diagram shows the dataset object model −


The DataSet class is present in the System.Data namespace. The following
table describes all the components of DataSet −

Sr.No
Components & Description
.

DataTableCollection
1
It contains all the tables retrieved from the data source.

DataRelationCollection
2
It contains relationships and the links between tables in a data set.

ExtendedProperties
3 It contains additional information, like the SQL statement for retrieving data, time of
retrieval, etc.

DataTable
4 It represents a table in the DataTableCollection of a dataset. It consists of the DataRow
and DataColumn objects. The DataTable objects are case-sensitive.

DataRelation
5 It represents a relationship in the DataRelationshipCollection of the dataset. It is used to
relate two DataTable objects to each other through the DataColumn objects.

DataRowCollection
6
It contains all the rows in a DataTable.

DataView
7 It represents a fixed customized view of a DataTable for sorting, filtering, searching,
editing and navigation.
PrimaryKey
8
It represents the column that uniquely identifies a row in a DataTable.

DataRow
It represents a row in the DataTable. The DataRow object and its properties and methods
9
are used to retrieve, evaluate, insert, delete, and update values in the DataTable. The
NewRow method is used to create a new row and the Add method adds a row to the table.

DataColumnCollection
10
It represents all the columns in a DataTable.

DataColumn
11
It consists of the number of columns that comprise a DataTable.

Connecting to a Database
The .Net Framework provides two types of Connection classes −

 SqlConnection − designed for connecting to Microsoft SQL Server.


 OleDbConnection − designed for connecting to a wide range of
databases, like Microsoft Access and Oracle.

Example 1
We have a table stored in Microsoft SQL Server, named Customers, in a
database named testDB. Please consult 'SQL Server' tutorial for creating
databases and database tables in SQL Server.

Let us connect to this database. Take the following steps −

 Select TOOLS → Connect to Database


 Select a server name and the database name in the Add Connection
dialog box.
M

 Click on the Test Connection button to check if the connection


succeeded.
 Add a DataGridView on the form.

 Click on the Choose Data Source combo box.


 Click on the Add Project Data Source link.

 This opens the Data Source Configuration Wizard.


 Select Database as the data source type
 Choose DataSet as the database model.

 Choose the connection already set up.


 Save the connection string.

 Choose the database object, Customers table in our example, and click
the Finish button.
 Select the Preview Data link to see the data in the Results grid −

When the application is run using Start button available at the Microsoft
Visual Studio tool bar, it will show the following window −
Example 2
In this example, let us access data in a DataGridView control using code.
Take the following steps −

 Add a DataGridView control and a button in the form.


 Change the text of the button control to 'Fill'.
 Double click the button control to add the required code for the Click
event of the button, as shown below −
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
'TODO: This line of code loads data into the
'TestDBDataSet.CUSTOMERS' table.
You can move, or remove it, as needed.

Me.CUSTOMERSTableAdapter.Fill(Me.TestDBDataSet.CUSTOMERS)
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs)


Handles Button1.Click
Dim connection As SqlConnection = New sqlconnection()
connection.ConnectionString = "Data Source=KABIR-DESKTOP; _
Initial Catalog=testDB;Integrated Security=True"
connection.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter _
("select * from Customers", connection)
Dim ds As DataSet = New DataSet()
adp.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
End Sub
End Class
 When the above code is executed and run using Start button available
at the Microsoft Visual Studio tool bar, it will show the following window

 Clicking the Fill button displays the table on the data grid view control

Creating Table, Columns and Rows


We have discussed that the DataSet components like DataTable, DataColumn
and DataRow allow us to create tables, columns and rows, respectively.

The following example demonstrates the concept −


Example 3
So far, we have used tables and databases already existing in our computer.
In this example, we will create a table, add columns, rows and data into it
and display the table using a DataGridView object.

Take the following steps −

 Add a DataGridView control and a button in the form.


 Change the text of the button control to 'Fill'.
 Add the following code in the code editor.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs)
Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub

Private Function CreateDataSet() As DataSet


'creating a DataSet object for tables
Dim dataset As DataSet = New DataSet()
' creating the student table
Dim Students As DataTable = CreateStudentTable()
dataset.Tables.Add(Students)
Return dataset
End Function

Private Function CreateStudentTable() As DataTable


Dim Students As DataTable
Students = New DataTable("Student")
' adding columns
AddNewColumn(Students, "System.Int32", "StudentID")
AddNewColumn(Students, "System.String", "StudentName")
AddNewColumn(Students, "System.String", "StudentCity")
' adding rows
AddNewRow(Students, 1, "Zara Ali", "Kolkata")
AddNewRow(Students, 2, "Shreya Sharma", "Delhi")
AddNewRow(Students, 3, "Rini Mukherjee", "Hyderabad")
AddNewRow(Students, 4, "Sunil Dubey", "Bikaner")
AddNewRow(Students, 5, "Rajat Mishra", "Patna")
Return Students
End Function

Private Sub AddNewColumn(ByRef table As DataTable, _


ByVal columnType As String, ByVal columnName As String)
Dim column As DataColumn = _
table.Columns.Add(columnName, Type.GetType(columnType))
End Sub

'adding data into the table


Private Sub AddNewRow(ByRef table As DataTable, ByRef id As
Integer,_
ByRef name As String, ByRef city As String)
Dim newrow As DataRow = table.NewRow()
newrow("StudentID") = id
newrow("StudentName") = name
newrow("StudentCity") = city
table.Rows.Add(newrow)
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs)


Handles Button1.Click
Dim ds As New DataSet
ds = CreateDataSet()
DataGridView1.DataSource = ds.Tables("Student")
End Sub
End Class
 When the above code is executed and run using Start button available
at the Microsoft Visual Studio tool bar, it will show the following window

 Clicking the Fill button displays the table on the data grid view control

You might also like