You are on page 1of 12

3/20/2016

Objectives
2

To:
Sort

and filter database data &


display data in a grid
Using the DataGridView Control
Selecting DataSet Rows

LAB
WORKING WITH DATABASES I
Using SQL Server DBs + Visual Studio

The SalesStaff table


4

Lab 4-1

The Table Design

Sample Rows

Objectives:
To display rows and columns from a table
Table SalesStaff, located in a database
Company.
Holds information collected about company sales
employees.

To allow users of your application to sort on


any column, delete rows, and insert new
rows.

3/20/2016

Lab 4-1
5

Locate the Company.mdf file


Step 1: Create a new Windows application named SalesStaff
1.
Step 2: Set the Text property of Form1 to Company SalesStaff
Table
Step 3: Drag a DataGridView control from the Toolbox window
onto the form. Click the smart tag in the upper-right corner of
the grid. You should see a small popup window named
DataGridView Tasks.
Step 4: Click the dropdown arrow next to Choose Data Source.
In the dialog that appears, click on Add Project Data Source.
6

Lab 4-1
7

Lab 4-1
8

Step 5: When the Data Source Configuration Wizard displays,


select the Database icon and click the Next button.
Step 6: The Choose a Database Model step appears next. Keep
the default selection (Dataset) and click the Next button.

Step 7: The wizard asks you to choose


your data connection.
If

you had an existing data connection, you


could select it from the dropdown list.
Because this is your first data connection,
click the New Connection button

3/20/2016

Lab 4-1
9

Lab 4-1
10

Step 8: In the Add Connection window, if the Data


source entry does not say Microsoft SQL Server
Database File, click the Change button and select that
option.

Lab 4-1
11

Step 9: Click the


Browse button and
locate
the
Company.mdf
database you have
been provided with.
The figure shows an
incomplete path to
the
Company.mdf
filename because the
actual path will be
different on each
computer.

Lab 4-1
12

Step 10: Click the Test Connection button. Assuming that the Test Connection
succeeded message displays, click the OK button two times to return to the
wizard, and then click the Next button.

Step 11: You will see the following message asking you if you want to copy
the database file to the project directory.

By answering yes, you can easily move your program and its database to
another computer. When you hand in programming projects, having the
database stored with the project is a good idea. Click the Yes button to continue.

Step 12: Now you are given the option of saving


the connection string to the application configuration
file (see figure below).
Leave the option checked and click the Next button
to continue.

3/20/2016

Lab 4-1
13

Lab 4-1
14

Step 13: Next, you are


asked to select which
database objects you
want in your DataSet.

Expand
the
entry
under Tables, place a
check next to SalesStaff,
and
change
the
DataSet
name
to
SalesStaffDataSet (see
figure).

Step 14: You should see column headings in the


DataGridView control (see Figure below)
that match the SalesStaff columns: ID, Last_Name,
First_Name, Full_Time, Hire_Date, Salary.
If the DataGridView Tasks window is still visible, click
anywhere outside the window to close it.

Click the Finish button


to
complete
the
wizard.

Lab 4-1

15

Step 15: Next, you will center the Hire_Date column.


Refer to the figure in the next slide.

3
2

Select the grids Columns property and open the Edit


Columns window.
Select the Hire_Date column, and select DefaultCellStyle.
This will display the CellStyle Builder window, shown in the
figure.
Select the Alignment property, and select MiddleCenter from
its dropdown list.
Click the OK buttons until the Edit Columns window is closed.

16

3/20/2016

Lab 4-1
17

Lab 4-1
18

Step 16: Open the forms Code window, and inspect the
code Visual Studio inserted into the forms Load event
handler.

The

TableAdapter pulls data from the database, using


the Fill method.
The Fill method holds an SQL query that determines
which columns of which table will be used.
The SalesStaff DataTable is a container that holds the
data while it is being displayed by the DataGridView
control.

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


Handles MyBase.Load
'TODO:
This
line
of
code
loads
data
into
the
'SalesStaffDataSet.SalesStaff' table. You can move, or remove
it, as needed.
Me.SalesStaffTableAdapter.Fill(Me.SalesStaffDataSet.SalesStaff)

End Sub

It calls the Fill method from the SalesStaffTableAdapter,


passing it the SalesStaff DataTable inside the
SalesStaffDataSet DataSet.

Lab 4-1

Lab 4-1

Showing the Salesstaff Table In A Datagridview Control


19

Step 16 (cont):
This is how the grid gets its data:

20

Step
17:
Save
and
run
the
application.
You should
see all the
rows of the
SalesStaff
table,
as
shown in the
figure.

Step 18: Sorting


Currently the rows are listed in ascending order by ID
number.
Click the Last_Name column and watch the grid sort the rows
in ascending order by last name.
Click the Last_Name column again and watch the rows sort in
descending order on the same column.

Step 19: Column Widths


Place the mouse over the border between two columns.
When the mouse cursor changes to a horizontal arrow, use
the mouse to drag the border to the right or left.
This is how users can change column widths at runtime.

3/20/2016

Lab 4-1

Lab 4-1
21

22

Step 20: Try deleting a row.

Step 22: Sort the grid on the Last_Name


column, and look for the row you inserted.
Step 23: Close the application and then run it
again to verify that the changes you made to
the DataSet were not saved in the database.

Click the button to the left of one of the grid rows. The
entire row is selected (highlighted).
Press the Del key and watch the row disappear.
The row has been removed from the in-memory DataSet, but
not the database.

Step 21: Next, you will insert a new row.

The

grid rows look exactly as they did when you


first displayed the DataSet.
Stop the program again.

Scroll to the bottom row of the grid and enter


the following information in the empty cells: 847, Jackson,
Ochieng, (check Full-time), 6/1/2011, 65000.
Press the Enter key to save your changes.

Lab 4-1
23

Lab 4-1 Exercise


24

Step 24: In Design view, notice the three components placed in


the forms component tray by Visual Studio when you added
the connection to the SalesStaff table.

Explain how to change the formatting of the Salary


column so it displays values in currency format.

If you cant see them run the prog and look at the forms design view.

SalesStaffDataSet is the object that holds a copy of the


database table in memory.
SalesStaffBindingSource is the object that moves data from
the dataset to the DataGridView control.
SalesStaffTableAdapter is the object that copies data from
the database into the dataset.

As another option, it can save changes to the database.


The TableAdapter contains the SQL statements that select, update,
insert, or delete database table rows.

3/20/2016

25

Exercise Answer
Formatting GridView Columns

26

To modify the columns in a


DataGridView
control,
open
the
DataGridView Tasks window and select
Edit Columns from the popup menu.
CellStyle Builder Window

Exercise Answer
Format Property

(CellStyle Builder window)


Format String dialog window:
For

general number formats, select Numeric and select


the number of decimal places.
For currency formats, select Currency and select the
number of decimal places.
For DateTime formats, select Date Time and select from
a variety of format samples.
For scientific formats, select Scientific and select the
number of decimal places.

use

it to select the column's alignment


(TopLeft, MiddleRight, and so on), padding,
format, foreground and background colors,
font, and so on.

Selecting DataSet Rows


28

27

Selecting DataSet Rows

Applications often must select (or filter) only certain


rows for display e.g. for our db we want to display:
only

members of the company sales staff


who are full-time or
employees hired prior to 2005 or
only those employees hired within the last five years
whose
salaries
are
less
than $40,000.

We filter rows using SQL queries and the tools in


Visual Studio.

3/20/2016

Modifying the Query in a Data


Source

Selecting DataSet Rows


29

30

Structured Query Language (SQL) is a


standard language for working with
databases.
Although SQL is a language, you dont use it to
write applications.

It

is intended only as a standard means of


interacting with a database.
You still need a general programming language
such as Visual Basic to write applications with user
interfaces.

To edit a query used in a data Dataset Designer tool


source, locate its DataSet
schema file in the Solution
table name
Explorer window.

DataSet Designer Window

Since we created a data source


named SalesStaffDataSet; then
the DataSet schema file is
named SalesStaffDataSet.xsd.

Double-click the filename to


open the Dataset Designer tool.
By
default,
the
SalesStaffTableAdapter has one
query named Fill, GetData()
that fills the DataSet when the
form loads.

The PK

The TableAdapter query list

Query Builder
32

31

Contains TableAdapters
and DataTables
Use it to view/modify
queries

right-click the DataSet


and
select Configure from the
popup menu,
you can modify the
currently selected query
using the TableAdapter
Configuration Wizard (see
figure)

If the query text is simple enough, you can modify it


directly in this window.
If the query is more complicated, click the Query
Builder button to display a Query Builder window
(see sample in figure).

3/20/2016

Query Builder

Query Builder

33

34

A tool provided by Visual


Studio for creating and
modifying SQL queries.

Consists of four sections,


called panes (see figure).

To remove and restore


panes, right-click
the
window and select Pane
from the popup menu.

The menu allows you to


check
or
uncheck
individual panes.

To add a new table to the


Query Builder window,
right-click
inside
the
diagram
pane
and
select Add Table from the
popup menu.
To save the current query
and close Query Builder,
click the OK button.

For creating SQL queries


Diagram pane

Grid pane

The diagram pane displays all the tables used in the


query,
with
a
check
mark
next
to
each field that will be used in the DataSet

add

The grid pane displays the query in a


spreadsheet-like format. You can choose a
sort order and enter a selection criteria.

tables, show relationships, select columns

select

columns, create aliases, set sort order, insert


conditional expressions

The SQL pane displays the actual SQL query that


corresponds to the tables and fields selected in the diagram
and grid panes. You can write queries directly into this pane.

SQL pane
directly

The results pane displays the rows returned by executing the


current SQL query. To fill the results pane, right-click in the
Query Builder window and select Run from the context menu.

35

Results pane
show

Adding a Query to a Grid

edit the SQL server query's text

output when the query executes

Adding a Query to a Grid


36

Use the TableAdapter object in the component tray:


In

the form's Design view,


right-click the TableAdapter icon and
select Add Query
the Search Criteria Builder window appears

You could modify the query so it reads as follows:


SELECT ID, Last_Name, First_Name,
Full_Time, Hire_Date, Salary FROM
SalesStaff WHERE Salary < 45000

You can give a name to the query, such as


Salary_query.
When you click the OK button, a ToolStrip control is
added to the form, with a query button.
When you run the application and click the
Salary_query button on the ToolStrip, only rows with
salaries less than $45,000 are displayed.

3/20/2016

Note
37

1.

If you dock a grid inside a form and then add a ToolStrip


control, the grids title bar is covered up by the ToolStrip.

2.

38

To avoid this problem, set the grids Dock property to None, drag the
grid a bit lower on the form with the mouse, and resize it so it fits.
Then set the grids Anchor property to Top, Bottom, Left, Right.

Objective
To create several queries that change the way rows
from the SalesStaff table are displayed in a
DataGridView control.

If you add a query to a dataset and then later delete the


query from the DataSet Designer window, your program may
not run.

Lab 4-2
Filtering Rows in the SalesStaff Table

If this happens, Visual Studio may have left behind some extra code
that had been added to the designer file when the query was
created.
To sort this out, select the Rebuild <projectName> command from
Visual Studios Build menu.

Lab 4-2
39

Lab 4-2
40

Step 1: close Visual Studio to release its lock on the


database file.

Copy the SalesStaff 1 folder you created in Lab 4-1 to a


new folder named SalesStaff 2.

Step 2: Open the project from the SalesStaff 2 folder


(the solution file will still be named SalesStaff 1.sln).
Step 3: Right-click the project name in the Solution
Explorer window, and choose Rename.

Rename the project SalesStaff 2.

Step 4: In the Design window for Form1, right-click the


SalesStaffTableAdapter control in the component tray (or click
the smart tag in the upper-right corner of the data grid) and
select Add Query from the popup menu.
Step 5: In the Search Criteria Builder window, name the query
Full_Time.
Set its query text to the following:

SELECT ID, Last_Name, First_Name,


Full_Time, Hire_Date, Salary
FROM dbo.SalesStaff
WHERE (Full_Time = 'True')

Step 6: Click the OK button to close the Search Criteria Builder.

10

3/20/2016

Lab 4-2
41

Lab 4-2
42

Step 7: If your grid column headers are hidden


behind the ToolStrip control, slide the grid downward
to expose the column headers.
Anchor it to the four sides of the form, using the
Anchor property.
Step 8: Save the project and run the application.
Click the Full_Time button and observe that only full-time
employees are displayed.
Close the application and return to Design mode.

Step 9: the source code generated by Visual Studio when the


ToolStripButton is added:

A method named Full_Time, is called using the SalesStaffTableAdapter


object.

The argument passed to the method is the SalesStaff table inside the
SalesStaffDataSet DataSet:

Private
Sub
Full_TimeToolStripButton_Click()
Handles Full_TimeToolStripButton.Click
Try

Me.SalesStaffTableAdapter.Full_Time(Me.SalesStaffDataSet.SalesStaff)

Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)

End Try
End Sub

Lab 4-2
43

Lab 4-2
44

Step 10: Now you will add another button to the ToolStrip that
displays all table rows.

Right-click the SalesStaffTableAdapter control, or click the smart tag


in the upper-right corner of the data grid and select Add Query.

Step 11: In the Search Criteria Builder, name the query


All_Rows, and keep the existing Query text.
Click the OK button to close the window and create the query.
Notice that a second ToolStrip has been added to the form, as
shown in the following figure:

Step 12: Again, you may need to adjust the


top of the grid so the column headings are
visible.
Step 13: Save the project.

Run

the application and click both query buttons.


display should alternate between displaying
all rows, and rows containing fulltime employees
only.

The

Step 14: End the application and close the


project.

11

3/20/2016

Note
45

The Code So Far


46
Public Class Form1

It is possible to place both query buttons on the same ToolStrip.


In Design mode, select one of the buttons and cut it.
Select the other toolbar and paste the button (press Ctrl-V).
2.
Both buttons should be on the same ToolStrip.
3.
Select and delete the empty ToolStrip.
4.
Open the Code window and observe that the Handles clause
has disappeared from the Click event handler associated with
the button you copied. Add the Handles clause back to the
method header. For example:
Handles All_RowsToolStripButton.Click

1.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


'TODO: This line of code loads data into the 'SalesStaffDataSet.SalesStaff' table. You
can move, or remove it, as needed.
Me.SalesStaffTableAdapter.Fill(Me.SalesStaffDataSet.SalesStaff)
End Sub
Private Sub Full_timeToolStripButton_Click(sender As Object, e As EventArgs)
Full_timeToolStripButton.Click
Try
Me.SalesStaffTableAdapter.Full_time(Me.SalesStaffDataSet.SalesStaff)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try

Handles

End Sub
Private Sub All_RowsToolStripButton_Click(sender As Object, e As EventArgs)
All_RowsToolStripButton.Click
Try
Me.SalesStaffTableAdapter.All_Rows(Me.SalesStaffDataSet.SalesStaff)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try

Handles

End Sub
End Class

Lab 4-2 Exercise


47

Write a WHERE clause in SQL that limits the


returned data to rows in which Salary is less than or
equal to $25,000.

12

You might also like