0% found this document useful (0 votes)
21 views92 pages

VBHTP2e 20-Beta

This document provides an overview of databases, specifically focusing on relational databases, SQL, and ADO.NET. It covers key concepts such as database structure, SQL queries, and the use of ADO.NET for data manipulation. The document also includes examples and common programming errors related to database management.

Uploaded by

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

VBHTP2e 20-Beta

This document provides an overview of databases, specifically focusing on relational databases, SQL, and ADO.NET. It covers key concepts such as database structure, SQL queries, and the use of ADO.NET for data manipulation. The document also includes examples and common programming errors related to database management.

Uploaded by

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

1

2
0
Database, SQL
and ADO.NET

 2007 Pearson Education, Inc. All rights reserved.


2

It is a capital mistake to theorize before one has data.


—Arthur Conan Doyle

Now go, write it before them in a table, and note


it in a book, that it may be for the time to come
for ever and ever.
—Holy Bible, Isaiah 30:8

Get your facts first, and then you can distort them
as much as you please.
—Mark Twain

I like two kinds of men:


domestic and foreign.
—Mae West
 2007 Pearson Education, Inc. All rights reserved.
3

OBJECTIVES
In this chapter you will learn:
 The relational database model.
 To write basic database queries in SQL.
 To add data sources to projects.
 To use the IDE’s drag-and-drop capabilities to display
database tables in applications.
 To use the classes of namespaces System.Data and
System.Data.SqlClient to manipulate databases.
 To use ADO.NET’s disconnected object model to
store data from a database in local memory.
 To create XML documents from data sources.

 2007 Pearson Education, Inc. All rights reserved.


4

20.1 Introduction
20.2 Relational Databases
20.3 Relational Database Overview: Books Database
20.4 SQL
20.4.1 Basic SELECT Query
20.4.2 WHERE Clause
20.4.3 ORDER BY Clause
20.4.4 Merging Data from Multiple Tables: INNER
JOIN
20.4.5 INSERT Statement
20.4.6 UPDATE Statement
20.4.7 DELETE Statement

 2007 Pearson Education, Inc. All rights reserved.


5

20.5 ADO.NET Object Model


20.6 Programming with ADO.NET: Extracting
Information from a Database
20.6.1 Displaying a Database Table in a
DataGridView
20.6.2 How Data Binding Works
20.7 Querying the Books Database
20.8 Programming with ADO.NET: Address Book Case
Study
20.9 Using a DataSet to Read and Write XML
20.10 Wrap-Up
20.11 Web Resources

 2007 Pearson Education, Inc. All rights reserved.


6

20.1 Introduction

• Database
– Organized collection of data
– Database management system (DBMS)
• Provides mechanisms for storing, organizing, retrieving and
modifying data
– SQL
• The international standard language used universally to
perform queries and to manipulate data
– Visual Basic programs communicate with databases and
manipulate their data through ADO.NET

 2007 Pearson Education, Inc. All rights reserved.


7

20.2 Relational Databases


• Relational Databases
– Logical representation of data
• Allows the data to be accessed independently of its physical
structure
– A relational database organizes data in tables
• Tables are composed of rows and columns in which values are
stored
– Primary key
• A column in a table that requires a unique value that cannot be
duplicated in other rows
- Guarantees that a primary key value can be used to uniquely
identify a row
• Composite key
- A primary key that is composed of two or more columns

 2007 Pearson Education, Inc. All rights reserved.


8

Fig. 20.1 | Employees table sample data.

 2007 Pearson Education, Inc. All rights reserved.


9

Fig. 20.2 | Result of selecting distinct Department and


Location data from the Employees table.

 2007 Pearson Education, Inc. All rights reserved.


10

20.3 Relational Database Overview:


Books Database
• Overview
– SQL Server database files typically end with the .mdf
(“master data file”) filename extension
– Foreign keys
• Can be specified when creating a table
• Helps maintain the Rule of Referential Integrity
- Every foreign key value must appear as another table’s
primary key value
• Allow related data in multiple tables to be selected from
those tables (joining the data)

 2007 Pearson Education, Inc. All rights reserved.


11

20.3 Relational Database Overview:


Books Database (Cont.)
• Entity-Relationship (ER) Diagram
– Shows the tables in the database and their relationships
– First compartment in each box contains the table’s name
– The names in italic font are primary keys
• A table’s primary key uniquely identifies each row in the table
• Every row must have a value in the primary key column, and the value of the
key must be unique in the table
- Known as the Rule of Entity Integrity
– The lines connecting the tables represent the relationships
among the tables
• The number on the end of these lines indicates a one-to-many relationship
– The line between the tables links the primary key to the
matching foreign key

 2007 Pearson Education, Inc. All rights reserved.


12

Column Description

AuthorID Author’s ID number in the database. In the Books database, this integer
column is defined as an identity column, also known as an autoincremented
column—for each row inserted in the table, the AuthorID value is increased
by 1 automatically to ensure that each row has a unique AuthorID. This is
the primary key.
FirstName Author’s first name (a string).
LastName Author’s last name (a string).

Fig. 20.3 | Authors table of the Books database.

 2007 Pearson Education, Inc. All rights reserved.


13

AuthorID FirstName LastName

1 Harvey Deitel
2 Paul Deitel
3 Andrew Goldberg
4 David Choffnes

Fig. 20.4 | Data from the Authors table of the Books database.

 2007 Pearson Education, Inc. All rights reserved.


14

Column Description

ISBN ISBN of the book (a string). The table’s primary key.


ISBN is an abbreviation for “International Standard Book
Number”—a numbering scheme that publishers
worldwide use to give every book a unique identification
number.
Title Title of the book (a string).
EditionNumber Edition number of the book (an integer).
Copyright Copyright year of the book (a string).

Fig. 20.5 | Titles table of the Books database.

 2007 Pearson Education, Inc. All rights reserved.


15

ISBN Title Edition- Copy-


Number right

0131426443 C How to Program 4 2004


0131450913 Internet & World Wide Web How 3 2004
to Program
0131483986 Java How to Program 6 2005
0131525239 Visual C# 2005 How to Program 2 2006
0131828274 Operating Systems 3 2004
0131857576 C++ How to Program 5 2005
0131869000 Visual Basic 2005 How to 3 2006
Program

Fig. 20.6 | Data from the Titles table of the Books database.

 2007 Pearson Education, Inc. All rights reserved.


16

Column Description

AuthorID The author’s ID number, a foreign key to the Authors table.


ISBN The ISBN for a book, a foreign key to the Titles table.

Fig. 20.7 | AuthorISBN table of the Books database.

 2007 Pearson Education, Inc. All rights reserved.


17

AuthorID ISBN AuthorID ISBN

1 0131869000 2 0131450913
1 0131525239 2 0131426443
1 0131483986 2 0131857576
1 0131857576 2 0131483986
1 0131426443 2 0131525239
1 0131450913 2 0131869000
1 0131828274 3 0131450913
2 0131828274 4 0131828274

Fig. 20.8 | Data from the AuthorISBN table of Books.

 2007 Pearson Education, Inc. All rights reserved.


18

Common Programming Error 20.1

Not providing a value for every column in


a primary key breaks the Rule of Entity
Integrity and causes the DBMS to report
an error.

 2007 Pearson Education, Inc. All rights reserved.


19

Common Programming Error 20.2

Providing the same value for the primary key


in multiple rows breaks the Rule of Entity
Integrity and causes the DBMS to report an
error.

 2007 Pearson Education, Inc. All rights reserved.


20

Fig. 20.9 | Entity-relationship diagram for the Books database.

 2007 Pearson Education, Inc. All rights reserved.


21

Common Programming Error 20.3

Providing a foreign-key value that does not


appear as a primary-key value in another
table breaks the Rule of Referential
Integrity and causes the DBMS to report an
error.

 2007 Pearson Education, Inc. All rights reserved.


22

SQL keyword Description

SELECT Retrieves data from one or more tables.


FROM Specifies the tables involved in a query. Required in
every query.
WHERE Specifies optional criteria for selection that determine
the rows to be retrieved, deleted or updated.
ORDER BY Specifies optional criteria for ordering rows (e.g.,
ascending, descending).
INNER JOIN Specifies optional operator for merging rows from
multiple tables.
INSERT Inserts rows in a specified table.
UPDATE Updates rows in a specified table.
DELETE Deletes rows from a specified table.

Fig. 20.10 | Common SQL keywords.

 2007 Pearson Education, Inc. All rights reserved.


23

20.4.1 SELECT Query


• SELECT keyword
– “Selects” rows and columns from one or more tables in a
database
– The basic form of a SELECT query is:
SELECT * FROM tableName
– (*) indicates that all the columns from the tableName table
should be retrieved
– The rows are not guaranteed to be returned in any
particular order
– To retrieve only specific columns from a table, replace the
asterisk (*) with a comma-separated list of the column
names

 2007 Pearson Education, Inc. All rights reserved.


24

20.4.2 WHERE Clause


• WHERE Clause
– Specify the selection criteria for the query
– The basic form of a query with selection criteria is:
SELECT columnName1, columnName2, … FROM tableName WHERE
criteria
– WHERE clause criteria can contain the relational operators <, >, <=, >=,
= (equality), <> (inequality) and LIKE, as well as the logical operators
AND, OR and NOT
• LIKE is used for pattern matching with wildcard characters

Example:
• SELECT AuthorID, FirstName, LastName
FROM Authors
WHERE LastName LIKE 'D%'

 2007 Pearson Education, Inc. All rights reserved.


25

AuthorID LastName

1 Deitel
2 Deitel
3 Goldberg
4 Choffnes

Fig. 20.11 | AuthorID and LastName data from the Authors table.

 2007 Pearson Education, Inc. All rights reserved.


26

Title EditionNumber Copyright

Java How to Program 6 2005


Visual C# 2005 How to Program 2 2006
C++ How to Program 5 2005
Visual Basic 2005 How to Program 3 2006

Fig. 20.12 | Titles with copyright dates after 2004 from table Titles.

 2007 Pearson Education, Inc. All rights reserved.


27

AuthorID FirstName LastName

1 Harvey Deitel
2 Paul Deitel

Fig. 20.13 | Authors from the Authors table whose last names start with D.

 2007 Pearson Education, Inc. All rights reserved.


28

AuthorID FirstName LastName

4 David Choffnes

Fig. 20.14 | The only author from the Authors table whose last name
contains h as the second letter.

 2007 Pearson Education, Inc. All rights reserved.


29

20.4.3 ORDER BY Clause

• ORDER BY Clause
– Rows in the result of a query can be sorted into ascending
or descending order

SELECT columnName1, columnName2, …

FROM tableName ORDER BY column ASC

– Multiple columns can be used for sorting with an ORDER


BY clause of the form
ORDER BY column1 sortingOrder, column2 sortingOrder, …

 2007 Pearson Education, Inc. All rights reserved.


30

AuthorID FirstName LastName

4 David Choffnes
1 Harvey Deitel
2 Paul Deitel
3 Andrew Goldberg

Fig. 20.15 | Authors from table Authors in ascending order by LastName.

 2007 Pearson Education, Inc. All rights reserved.


31

AuthorID FirstName LastName

3 Andrew Goldberg
1 Harvey Deitel
2 Paul Deitel
4 David Choffnes

Fig. 20.16 | Authors from table Authors in descending order by LastName.

 2007 Pearson Education, Inc. All rights reserved.


32

20.4.4 Merging Data from Multiple Tables:


INNER JOIN
• Normalize databases
– Split related data into separate tables
• Ensure that a database does not store redundant data
• Merge data from multiple tables into a single result
– AKA “joining the tables”
– Specified by an INNER JOIN operator in the query
• Merges rows from two tables by testing for matching values in a
column that is common to the tables
SELECT columnName1, columnName2, …
FROM table1 INNER JOIN table2
ON table1.columnName = table2.columnName
• ON clause
- Specifies the columns from each table that are compared to
determine which rows are merged

 2007 Pearson Education, Inc. All rights reserved.


33

Title EditionNumber Copyright

Visual Basic 2005 How to Program 3 2006


Visual C# 2005 How to Program 2 2006
C++ How to Program 5 2005
Java How to Program 6 2005
C How to Program 4 2004
Internet & World Wide Web How to Program 3 2004
Operating Systems 3 2004

Fig. 20.17 | Data from Titles in descending order by Copyright and


ascending order by Title.

 2007 Pearson Education, Inc. All rights reserved.


34

ISBN Title EditionNumber Copyright

0131426443 C How to Program 4 2004


0131857576 C++ How to Program 5 2005
0131450913 Internet & World Wide Web 3 2004
How to
Program
0131483986 Java How to Program 6 2005
0131869000 Visual Basic 2005 How to 3 2006
Program
0131525239 Visual C# 2005 How to 2 2006
Program

Fig. 20.18 | Books from table Titles whose titles end with How to Program in
ascending order by Title.

 2007 Pearson Education, Inc. All rights reserved.


35

Common Programming Error 20.4

In a SQL query, failure to qualify names for


columns that have the same name in two or
more tables is an error.

 2007 Pearson Education, Inc. All rights reserved.


36

20.4.5 INSERT Statement


• INSERT Statement
– Inserts a row into a table

INSERT INTO tableName ( columnName1, columnName2, …, columnNameN


VALUES ( value1, value2, …, valueN )

– The tableName is followed by a comma-separated list of column names


in ( )
• List is not required if value for every column of the table in the correct order
– The list of column names is followed by the SQL keyword VALUES and
a comma-separated list of values in ( )
• Must match up with the columns specified after the table name in both order
and type
– Always explicitly list the columns when inserting rows
• If the ordering changes, using only VALUES may cause an error
– Not every DBMS supports identity or auto incremented columns

 2007 Pearson Education, Inc. All rights reserved.


37

Fig. 20.19 | Authors and ISBNs for their books in ascending order by
LastName and FirstName.

 2007 Pearson Education, Inc. All rights reserved.


38

Common Programming Error 20.5

It is an error to specify a value for an


identity column.

 2007 Pearson Education, Inc. All rights reserved.


39

Common Programming Error 20.6

SQL uses the single-quote (') character to delimit strings.


To specify a string containing a single quote (e.g.,
O’Malley) in a SQL statement, there must be two single
quotes in the position where the single-quote character
appears in the string (e.g., 'O''Malley'). The first of
the two single-quote characters acts as an escape
character for the second. Not escaping single-quote
characters in a string that is part of a SQL statement is a
syntax error.

 2007 Pearson Education, Inc. All rights reserved.


40

20.4.6 UPDATE Statement

• UPDATE Statement
– Modifies data in a table
UPDATE tableName
SET columnName1 = value1, …, columnNameN = valueN
WHERE criteria
– The tableName is followed by keyword SET and a comma-
separated list of column name-value pairs in the format
columnName = value
– WHERE clause
• Optional
• Provides criteria that determine which rows to update

 2007 Pearson Education, Inc. All rights reserved.


41

AuthorID FirstName LastName

1 Harvey Deitel
2 Paul Deitel
3 Andrew Goldberg
4 David Choffnes
5 Sue Smith

Fig. 20.20 | Table Authors after an INSERT operation.

 2007 Pearson Education, Inc. All rights reserved.


42

20.4.7 DELETE Statement

• DELETE Statement
– Removes rows from a table
DELETE FROM tableName WHERE criteria
– WHERE clause
• Optional
• Specifies the criteria used to determine which rows to delete

 2007 Pearson Education, Inc. All rights reserved.


43

AuthorID FirstName LastName

1 Harvey Deitel
2 Paul Deitel
3 Andrew Goldberg
4 David Choffnes
5 Sue Jones

Fig. 20.21 | Table Authors after an UPDATE operation.

 2007 Pearson Education, Inc. All rights reserved.


44

AuthorID FirstName LastName

1 Harvey Deitel
2 Paul Deitel
3 Andrew Goldberg
4 David Choffnes

Fig. 20.22 | Table Authors after a DELETE operation.

 2007 Pearson Education, Inc. All rights reserved.


45

20.5 ADO.NET Object Model


• ADO.NET
– Provides an API for accessing database systems programmatically
– Replace Microsoft's ActiveX Data Objects (ADO) technology
– System.Data is the root namespace for the ADO.NET API
• Class DataTable
- Represents a table of data
- Contains a collection of DataRows and DataColumns
• System.Data.DataSet
- Consists of a set of DataTables and the relationships among them
- Represents a cache of data
• System.Data.OleDb
- Contains classes that are designed to work with any data source

 2007 Pearson Education, Inc. All rights reserved.


46

20.5 ADO.NET Object Model (Cont.)

• System.Data.SqlClient
– Contains classes that are optimized to work with Microsoft
SQL Server databases
– Class SqlConnection
• Represents a connection to a data source
- Keep tracks of the location of the data source and how it is
accessed
– Class SqlCommand
• Represents a SQL command that a DBMS can execute on a
database
– Class SqlConnection
• Represents a connection to a data source

 2007 Pearson Education, Inc. All rights reserved.


47

20.5 ADO.NET Object Model (Cont.)

•System.Data.SqlClient
– Contains classes that are optimized to work with
Microsoft SQL Server databases
– Class SqlConnection
• Represents a connection to a data source
- Keep tracks of the location of the data source and how it
is accessed
– Class SqlCommand
• Represents a SQL command that a DBMS can execute on a
database

 2007 Pearson Education, Inc. All rights reserved.


48

20.5 ADO.NET Object Model (Cont.)


• ADO.NET’s Disconnected Model
– DataSets that is disconnected does not need a
persistent connection to work with data
– Connect to the data source to populate the
DataSet, and disconnects immediately afterwards
• Access and manipulate the data stored in the DataSet
• If necessary, reconnect to perform an update and then disconnect
– Class SqlDataAdapter
• Connects to a SQL data source
• Executes SQL statements to both populate and update the a
DataSet
• Maintains a SqlConnection object that it opens and closes as
needed to perform these operations using SqlCommands

 2007 Pearson Education, Inc. All rights reserved.


49

20.6 Programming with ADO.NET:


Extracting Information from a Database
• The IDE provides visual programming tools and
wizards that simplify accessing data in your projects
– These tools establish database connections and create the
ADO.NET to view and manipulate the data through GUI
controls

 2007 Pearson Education, Inc. All rights reserved.


50

20.6.1 Displaying a Database Table in a


DataGridView
• DataGridView component
– Displays a data source in a GUI
– Displays data organized in rows and columns
• Connection string
– Specifies the path to a database file
– Determine how the database is accessed
• Adding a data source causes the IDE to generate a class
derived from System.Data.DataSet
– Designed specifically to store data from that data source
• BindingNavigator component
– Provides several ways for users to browse and manipulate data
displayed by another GUI control on a Form

 2007 Pearson Education, Inc. All rights reserved.


51

20.6.1 Displaying a Database Table in a


DataGridView (Cont.)
• Step 1: Create the Project
• Step 2: Add a Data Source to the Project (Fig. 20.23)
• Step 3: Choose the Data Source Type to Add to the Project
(Fig. 20.24)
• Step 4: Add a New Database Connection (Fig. 20.25)
• Step 5: Choose the Books.mdf Data Connection (Fig. 20.26)
• Step 6: Save the Connection String (Fig. 20.27)
• Step 7: Select the Database Objects to Include in Your DataSet
(Fig. 20.28)
• Step 8: View the Data Source in the Data Sources Window (Fig. 20.29)
• Step 9: View the Database in the Solution Explorer (Fig. 20.30)

 2007 Pearson Education, Inc. All rights reserved.


52

Fig. 20.23 | Adding a data source to a project.

 2007 Pearson Education, Inc. All rights reserved.


53

Fig. 20.24 | Choosing the data source type in the Data Source Configuration Wizard.

 2007 Pearson Education, Inc. All rights reserved.


54

Fig. 20.25 | Adding a new data connection.

 2007 Pearson Education, Inc. All rights reserved.


55

Fig. 20.26 | Choosing the Books.mdf data connection.

 2007 Pearson Education, Inc. All rights reserved.


56

Fig. 20.27 | Saving the connection string to the application configuration file.

 2007 Pearson Education, Inc. All rights reserved.


57

Fig. 20.28 | Choosing the database objects to include in the DataSet.

 2007 Pearson Education, Inc. All rights reserved.


58

Fig. 20.29 | Viewing a data source listed in the Data Sources window.

 2007 Pearson Education, Inc. All rights reserved.


59

Fig. 20.30 | Viewing a database listed in the Solution Explorer.

 2007 Pearson Education, Inc. All rights reserved.


60

Fig. 20.31 | Design view after dragging the Authors data source node to the Form.

 2007 Pearson Education, Inc. All rights reserved.


61

Fig. 20.32 | Displaying the Authors table in a DataGridView.

 2007 Pearson Education, Inc. All rights reserved.


62

20.6.1 Displaying a Database Table in a


DataGridView (Cont.)
• By default, a new copy of the database file is used
each time you run the application
– Any changes made to the database
• To allow changes to be made to the database file:
– Select the database file in the Solution Explorer
– Change its Copy to Output Directory property to
Copy if newer in the Properties window

 2007 Pearson Education, Inc. All rights reserved.


63

20.6.2 How Data Binding Works


• Data Binding
– Technique in which GUI controls are connected to data sources
• Changes made through the application to the underlying data source will
automatically be reflected in the data-bound control
• Modifying the data in the data-bound control and saving the changes updates
the underlying data source
– The structure of an untyped DataSet is determined at runtime
• Based on the results of a specific query
– The structure of a strongly typed DataSet is known at compile time
• It is created specifically to store data from a particular data source
– A TableAdapter is responsible for interacting with a database on disk
• Encapsulates a SqlDataAdapter object
• Method Fill
- Retrieves information from the database and places it in the DataSet

 2007 Pearson Education, Inc. All rights reserved.


64

20.6.2 How Data Binding Works (Cont.)

– BindingSource
• Identifies a data source that a program can bind to a
control
• Serves as an intermediary between the data source and
the corresponding data-bound GUI control
- Method EndEdit
• Applies changes made to data through a GUI control
to the data source bound to that control

 2007 Pearson Education, Inc. All rights reserved.


65

Fig. 20.33 | Data binding architecture used to display the Authors


table of the Books database in a GUI.

 2007 Pearson Education, Inc. All rights reserved.


1 ' Fig. 20.34: FrmDisplayTable.vb 66
' Displays data from a database table in a DataGridView.
2
3 Public Class FrmDisplayTable
Outline
4 ' Click event handler for the Save Button in the
5 ' BindingNavigator saves the changes made to the data
6 Private Sub AuthorsBindingNavigatorSaveItem_Click( _
FrmDisplayTable
7 ByVal sender As System.Object, ByVal e As System.EventArgs) _
.vb
8 Handles AuthorsBindingNavigatorSaveItem.Click
9 Ensure that the object’s associated
10 Me.Validate() data source is updated
11 Me.AuthorsBindingSource.EndEdit()
12 Me.AuthorsTableAdapter.Update(Me.BooksDataSet.Authors)
13 End Sub ' AuthorsBindingNavigatorSaveItem_Click
Write the modified version of the
14
15 ' loads data into the BooksDataSet.Authors table,
Authors table to the database
16 ' which is then displayed in the DataGridView
17 Private Sub FrmDisplayTable_Load(ByVal sender As System.Object, _
18 ByVal e As System.EventArgs) Handles MyBase.Load
19 ' TODO: This line of code loads data into the 'BooksDataSet.Authors'
20 ' table. You can move, or remove it, as needed.
Retrieve information from the
21 Me.AuthorsTableAdapter.Fill(Me.BooksDataSet.Authors)
22 End Sub ' FrmDisplayTable_Load
database and place this
23 End Class ' FrmDisplayTable information in the DataSet

 2007 Pearson Education,


Inc. All rights reserved.
67

20.7 Querying the Books Database


• Step 1: Create the Project
• Step 2: Add a Data Source to the Project
• Step 3: Create a DataGridView to Display the Titles Table
• Step 4: Add Custom Queries to the TitlesTableAdapter (Fig. 20.35)
• Step 5: Choose How the TableAdapter Should Access the Database (Fig. 20.36)
• Step 6: Choose a Query Type (Fig. 20.37)
• Step 7: Specify a SELECT Statement for the Query (Fig. 20.38)
• Step 8: Build a Query with Query Builder (Fig. 20.39)
• Step 9: Close the Query Builder (Fig. 20.40)
• Step 10: Set the Names of the Autogenerated Methods That Perform the Query (Fig. 20.41-2)
• Step 11: Add an Additional Query
• Step 12: Add a ComboBox to the Form
• Step 13: Customize the Form’s Load Event Handler
• Step 14: Program an Event Handler for the ComboBox (Fig. 20.43)
 2007 Pearson Education, Inc. All rights reserved.
68

Fig. 20.35 | Viewing the BooksDataSet in the Dataset Designer.

 2007 Pearson Education, Inc. All rights reserved.


69

Fig. 20.36 | TableAdapter Query Configuration Wizard to add a query


to a TableAdapter.

 2007 Pearson Education, Inc. All rights reserved.


70

Fig. 20.37 | Choosing the type of query to be generated for the TableAdapter.

 2007 Pearson Education, Inc. All rights reserved.


71

Fig. 20.38 | Specifying a SELECT statement for the query.

 2007 Pearson Education, Inc. All rights reserved.


72

Fig. 20.39 | Query Builder after adding a WHERE clause by entering a


value in the Filter column. (Part 1 of 2.)

 2007 Pearson Education, Inc. All rights reserved.


73

Fig. 20.39 | Query Builder after adding a WHERE clause by entering a


value in the Filter column. (Part 2 of 2.)

 2007 Pearson Education, Inc. All rights reserved.


74

Fig. 20.40 | The SELECT statement created by the Query Builder.

 2007 Pearson Education, Inc. All rights reserved.


75

Fig. 20.41 | Specifying names for the methods to be added to the


TitlesTableAdapter.

 2007 Pearson Education, Inc. All rights reserved.


76

Fig. 20.42 | Dataset Designer after adding Fill and Get methods to the
TitlesTableAdapter.

 2007 Pearson Education, Inc. All rights reserved.


1 ' Fig. 20.43: FrmDisplayQueryResult.vb 77
' Displays the result of a user-selected query in a DataGridView.
2
3 Public Class FrmDisplayQueryResult
Outline
4 ' Click event handler for the Save Button in the
5 ' BindingNavigator saves the changes made to the data
6 Private Sub TitlesBindingNavigatorSaveItem_Click( _
FrmDisplayQuery
7 ByVal sender As System.Object, ByVal e As System.EventArgs) _
Result.vb
8 Handles TitlesBindingNavigatorSaveItem.Click
9
10 Me.Validate()
(1 of 3 )
11 Me.TitlesBindingSource.EndEdit()
12 Me.TitlesTableAdapter.Update(Me.BooksDataSet.Titles)
13 End Sub ' TitlesBindingNavigatorSaveItem_Click
14
15 ' loads data into the BooksDataSet.Titles table,
16 ' which is then displayed in the DataGridView
17 Private Sub FrmDisplayQueryResult_Load(ByVal sender As System.Object, _
18 ByVal e As System.EventArgs) Handles MyBase.Load
19 ' TODO: This line of code loads data into the 'BooksDataSet.Titles'
20 ' table. You can move, or remove it, as needed.
21 Me.TitlesTableAdapter.Fill(Me.BooksDataSet.Titles)
22
23 ' set the ComboBox to show the default query that
24 ' selects all books from the Titles table
25 cboQueries.SelectedIndex = 0
26 End Sub ' FrmDisplayQueryResult_Load
27

 2007 Pearson Education,


Inc. All rights reserved.
28 ' loads data into the BooksDataSet.Titles table based on 78
29 ' user-selected query
Outline
30 Private Sub cboQueries_SelectedIndexChanged( _
31 ByVal sender As System.Object, ByVal e As System.EventArgs) _
32 Handles cboQueries.SelectedIndexChanged
33 ' fill the Titles DataTable with the result of the selected query FrmDisplayQuery
34 Select Case cboQueries.SelectedIndex Result.vb
35 Case 0
36 TitlesTableAdapter.Fill(BooksDataSet.Titles) Executes a SELECT
(2 of 3query
) that
37 Case 1 ' books with copyright year 2006 selects all rows
38 TitlesTableAdapter.FillWithCopyright2006(BooksDataSet.Titles)
39 Case 2 ' How to Program books, sorted by Title
40 TitlesTableAdapter.FillWithHowToProgramBooks( _ Executes a SELECT query that
41 BooksDataSet.Titles)
selects all rows in which the
42 End Select
copyright year is 2006
43 End Sub ' cboQueries_SelectedIndexChanged
44 End Class ' FrmDisplayQueryResult
Executes a query that selects all
rows that have “How To
Program” at the end of their
titles and sorts them in
ascending order by title

 2007 Pearson Education,


Inc. All rights reserved.
79
Outline

FrmDisplayQuery
Result.vb

(3 of 3 )

 2007 Pearson Education,


Inc. All rights reserved.
80

20.8 Programming with ADO.NET:


Address Book Case Study
• Step 1: Create the Project
• Step 2: Add the Database to the Project
• Step 3: Indicating that the IDE Should Create a Set of Labels and TextBoxes to Display
Each Row of Data (Fig. 20.45)
• Step 4: Drag the Addresses Data Source Node to the Form (Fig. 20.46)
• Step 5: Make the AddressID TextBox ReadOnly
• Step 6: Running the Application
• Step 7: Add a Query to the AddressesTableAdapter (Fig. 20.47)
– An @ symbol is used to indicate a parameter that will be replaced by a value when the query is executed

• Step 8: Add Controls to Allow Users to Specify a Last Name to Locate (Fig. 20.48)
• Step 9: Program an Event Handler That Locates the User-Specified Last Name (Fig. 20.44)
• Step 10: Allow the User to Return to Browsing All Rows in the Database (Fig. 20.44)

 2007 Pearson Education, Inc. All rights reserved.


1 ' Fig. 20.44: FrmAddressBook.vb 81
' Allows users to manipulate an address book.
2
3 Public Class FrmAddressBook
Outline
4 ' Click event handler for the Save Button in the
5 ' BindingNavigator saves the changes made to the data
6 Private Sub AddressesBindingNavigatorSaveItem_Click( _
FrmAddressBook
7 ByVal sender As System.Object, ByVal e As System.EventArgs) _
.vb
8 Handles AddressesBindingNavigatorSaveItem.Click
9
10 Me.Validate()
(1 of 3 )
11 Me.AddressesBindingSource.EndEdit()
12 Me.AddressesTableAdapter.Update(Me.AddressBookDataSet.Addresses)
13 End Sub ' AddressesBindingNavigatorSaveItem_Click
14
15 ' loads data into the AddressBookDataSet.Addresses table
16 Private Sub FrmAddressBook_Load(ByVal sender As System.Object, _
17 ByVal e As System.EventArgs) Handles MyBase.Load
18 ' TODO: This line of code loads data into the
19 ' 'AddressBookDataSet.Addresses' table. You can move, or remove
20 ' it, as needed.
21 Me.AddressesTableAdapter.Fill(Me.AddressBookDataSet.Addresses)
22 End Sub ' FrmAddressBook_Load
23

 2007 Pearson Education,


Inc. All rights reserved.
24 ' loads data for the rows with the specified last name 82
25 ' into the AddressBookDataSet.Addresses table
Outline
26 Private Sub btnFind_Click(ByVal sender As System.Object, _
27 ByVal e As System.EventArgs) Handles btnFind.Click
28 ' fill the DataSet's DataTable with only rows
29 ' containing the user-specified last name FrmAddressBook
30 AddressesTableAdapter.FillByLastName( _ .vb
31 AddressBookDataSet.Addresses, txtFind.Text)
Executes a SELECT query that
32 End Sub ' btnFind_Click (2 rows
selects all of 3 )in which the
33
34 ' reloads AddressBookDataSet.Addresses with all rows
last name matches
35 Private Sub btnBrowseAll_Click(ByVal sender As System.Object, _
36 ByVal e As System.EventArgs) Handles btnBrowseAll.Click
37 ' fill the DataSet's DataTable with all rows in the database
38 AddressesTableAdapter.Fill(AddressBookDataSet.Addresses)
39
40 txtFind.Text = "" ' clear Find TextBox
41 End Sub ' btnBrowseAll_Click
Executes a SELECT query
42 End Class ' FrmAddressBook
that selects all rows

 2007 Pearson Education,


Inc. All rights reserved.
83
Outline

FrmAddressBook
.vb

(3 of 3 )

 2007 Pearson Education,


Inc. All rights reserved.
84

Fig. 20.45 | Selecting the control(s) to be created when dragging and dropping
a data source member onto the Form.

 2007 Pearson Education, Inc. All rights reserved.


85

Fig. 20.46 | Displaying a table on a Form using a series of Labels and TextBoxes.

 2007 Pearson Education, Inc. All rights reserved.


86

Fig. 20.47 | Dataset Designer for the AddressBookDataSet after adding


a query to AddressesTableAdapter.

 2007 Pearson Education, Inc. All rights reserved.


87

Fig. 20.48 | Design view after adding controls to locate a last


name in the address book.

 2007 Pearson Education, Inc. All rights reserved.


88

Fig. 20.49 | Viewing the DataBindings.Text property of a TextBox


in the Properties window.

 2007 Pearson Education, Inc. All rights reserved.


89

20.9 Using a DataSet to Read and Write


XML
• ADO.NET has the ability to convert data stored in a data
source to XML
– For exchanging data between applications in a portable format
– Class DataSet of namespace System.Data
• Create XML documents from data sources
• Convert data from XML into data sources
- Method WriteXml
• Writes the XML representation of the DataSet instance
to a file
- Method ReadXml
• Reads the XML representation of the file into its own
DataSet
- Method GetXml
• Returns a String containing the XML representation of a
DataSet

 2007 Pearson Education, Inc. All rights reserved.


1 ' Fig. 20.50: FrmXMLWriter.vb 90
' Demonstrates generating XML from an ADO.NET DataSet.
2
3 Public Class FrmXMLWriter
Outline
4 ' Click event handler for the Save Button in the
5 ' BindingNavigator saves the changes made to the data
6 Private Sub PlayersBindingNavigatorSaveItem_Click( _
FrmXMLWriter.vb
7 ByVal sender As System.Object, ByVal e As System.EventArgs) _
8 Handles PlayersBindingNavigatorSaveItem.Click
9
(1 of 2 )
10 Me.Validate()
11 Me.PlayersBindingSource.EndEdit()
12 Me.PlayersTableAdapter.Update(Me.BaseballDataSet.Players)
13 End Sub ' PlayersBindingNavigatorSaveItem_Click
14
15 ' loads data into the BaseballDataSet.Players table
16 Private Sub FrmXMLWriter_Load(ByVal sender As System.Object, _
17 ByVal e As System.EventArgs) Handles MyBase.Load
18 ' TODO: This line of code loads data into the
19 ' 'BaseballDataSet.Players' table. You can move, or remove it,
20 ' as needed.
21 Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players)
22 End Sub ' FrmXMLWriter_Load

 2007 Pearson Education,


Inc. All rights reserved.
23 91
24 ' write XML representation of DataSet when Button clicked Set BaseballDataSet’s
Outline
25 Private Sub btnWrite_Click(ByVal sender As System.Object, _ Namespace property to specify
26 ByVal e As System.EventArgs) Handles btnWrite.Click
a namespace for the DataSet
27 ' set the namespace for this DataSet
28 ' and the resulting XML document FrmXMLWriter.vb
29 BaseballDataSet.Namespace = "http://www.deitel.com/baseball"
30 (2 of 2 )
31 ' write XML representation of DataSet to a file
32 BaseballDataSet.WriteXml("Players.xml")
33
Generates an XML representation
34 ' display XML representation in TextBox
of the data contained in the
35 txtOutput.Text = "Writing the following XML:" & vbCrLf & _ DataSet and then write the
36 BaseballDataSet.GetXml() + vbCrLf XML to the specified file
37 End Sub ' btnWrite_Click
38 End Class ' FrmXMLWriter Returns a String containing the XML

 2007 Pearson Education,


Inc. All rights reserved.
1 <?xml version="1.0" standalone="yes"?> 92
<BaseballDataSet xmlns="http://www.deitel.com/baseball">
2
3 <Players>
Outline
4 <PlayerID>1</PlayerID> Declares the document’s default
5 <FirstName>John</FirstName> namespace
6 <LastName>Doe</LastName>
7 <BattingAverage>0.375</BattingAverage>
8 </Players>
9 <Players> Each Players element represents a
10 <PlayerID>2</PlayerID> record in the Players table
11 <FirstName>Jack</FirstName>
12 <LastName>Smith</LastName>
13 <BattingAverage>0.223</BattingAverage>
14 </Players>
15 <Players>
16 <PlayerID>3</PlayerID>
17 <FirstName>George</FirstName>
18 <LastName>O'Malley</LastName>
19 <BattingAverage>0.344</BattingAverage>
20 </Players>
21 </BaseballDataSet>

 2007 Pearson Education,


Inc. All rights reserved.

You might also like