13
1 McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved. 3-1 Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good OOP principles and perform the database access in a datatier component. You will learn to use table adapters and DataSets to display data from a database file. Chapter 3 McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved. 3-3 Objectives (1 of 2) Retrieve and display data from a SQL Server database on Windows forms. Use the ADO.NET data components: TableAdapters, DataSets, and DataConnectors. Display database fields in a grid and in details view. Sort database data using a method and an SQL query. Concatenate data fields using SQL or the DataSet Designer.

Chapter 3 Windows Database Applications - … · Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good

Embed Size (px)

Citation preview

Page 1: Chapter 3 Windows Database Applications - … · Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good

1

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-1

Windows DatabaseApplications

In this chapter, you learn to access and display database data on a Windows form. You will follow good OOP principles and perform the database access in a datatier component. You will learn to use table adapters and DataSets to display data

from a database file.

Cha

pter

3

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-3

Objectives (1 of 2)

Retrieve and display data from a SQL Server database on Windows forms.Use the ADO.NET data components: TableAdapters, DataSets, and DataConnectors.Display database fields in a grid and in details view.Sort database data using a method and an SQL query.Concatenate data fields using SQL or the DataSetDesigner.

Page 2: Chapter 3 Windows Database Applications - … · Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good

2

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-4

Objectives (2 of 2)

Access data using a stored procedure.Write a multitier application that separates the data tier from the presentation tier.Declare and instantiate DataSet and TableAdapterobjects in code and write the code to bind data to form controls.

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-5

VS 2005 and Database ApplicationsProfessional VB programmers spend the majority of time on applications involving databasesThe managed providers included in the .NET Framework:

The .NET Framework Data Provider for:SQL ServerOLEDB (i.e., Access)SQL Server Mobile EditionOracleODBC (other database formats)

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-6

Universal Data Access (UDA)

Microsoft’s strategy for accessing data for multiple providersGoal is to access any type of data from any application on any type of computer

Page 3: Chapter 3 Windows Database Applications - … · Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good

3

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-7

OLEDB

Technology designed to implement the UDA conceptStandardized interface that allows reference to data from any source using the same programming toolsUsing OLEDB, programmers don’t need to be concerned with syntax of a particular data format

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-8

ADO.NET 2.0 (1 of 2)

Microsoft’s latest database object modelAllows VB programmers to use a standard set of objects to refer to data from any source.NET approach uses disconnected datasets with common data representation (data types) from multiple sources

ActiveX Data Objects ADO

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-9

ADO.NET (2 of 2).NET framework is integrated with XML (Extensible Markup Language)

Multitier applications that use disconnected datasets provide for

Flexibility adapt to changes in data or presentation tierScalability handle increases in the number of users and servers

XML is an industry standard format for storing andtransferring data over multiple platforms.

Page 4: Chapter 3 Windows Database Applications - … · Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good

4

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.

Business tierBusiness tier Data tierData tier

Presentation tierPresentation tierWindows formsWindows forms

Web formsWeb forms

Business to businessBusiness to business

Data object (class)Data object (class)

DatasetDataset

DatasetDatasetDatasetDataset

InternetInternetintranetintranet Table adapterTable adapter

Table adapterTable adapter

(BizTalk, for example)(BizTalk, for example)

XmlXml

Myapp.ExeMyapp.Exe

IEIE

ADO .NET Architecture

Ken Getz MCW Technologies, LLCKen Getz MCW Technologies, LLC

Binding Source and/orBinding Source and/orBinding Navigator Binding Navigator

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-11

Accessing Data in the .NET Framework

Terminology for working with dataData sourcesData designersDatasetsBinding sourcesTable adaptersAnd more

Still used are many of the standard terms for data elements

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-12

Databases

A data table consists of rows and columnsEach row represents the data for one item, person or transaction and is called a recordEach column represents a different element of data and is called a fieldA primary key field (or combination of fields) uniquely identifies each record

Page 5: Chapter 3 Windows Database Applications - … · Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good

5

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-13

Data Sources

Data Sources can be created from large-scale databases, local databases, files, or other objectsA typed DataSet is added when a data source is created from a database file

Each typed DataSet has a schema which describes the fields and their data types

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.

DataSet Objects

DataSet Objects hold a copy of the data in memoryA temporary cache rather than the actual database data

Regardless of the data source, code handles DataSetobjects the sameDataset objects hold one or more DataTable objects

A relationship ties the tables together

3-14

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-15

The DataSet Object Model

Page 6: Chapter 3 Windows Database Applications - … · Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good

6

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-16

TableAdaptersA TableAdaptor object provides communication between a program and a database; sometimes called the “data access layer”Connects to the database and handles SQL queries and stored procedures, fills the DataSets, and handles writing changes back in the data sourceCan hold multiple queriesData is retrieved by calling a specific query or getting all of the data for the tableVisual designers in the VS IDE automatically generate Table Adapters when a typed DataSet is added

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-17

BindingSource Objects

Facilitates binding the controls on a Windows form to a data sourceHandles the navigation, sorting, filtering and updating of dataKeeps all of the form’s controls displaying data from the same record

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-18

XML Data

XML is generated automaticallyData stored in XML is all text, identified by tags, similar to HTMLXML files can be edited by any text editorTags identify fields by nameSpecs found for XML at http://www.w3.org/XML

XML is an industry standard format for storing andtransferring data.

See code p. 114

Page 7: Chapter 3 Windows Database Applications - … · Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good

7

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-19

DataSet Schema

Describes the fields, data types, and constraints, such as required fieldsADO.NET validates the data against the schema and checks for constraint violationsADO.NET can treat the XML data as objectsData handling in XML and ADO.NET executes faster than in earlier forms of ADO

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-20

Visual Studio IDE and Data Sources Window

IDE provides tools to assist in developing database applicationsUse the Data Sources window to create data-bound controls on a formUsed to add and view the DataSets that are used in a project

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-21

Local Database Files

VS 2005 offers an option to make a copy of the database file inside the project if project is based on a database file

This is a duplicate of the original fileCan be used for development and testingCan move the project from one folder or computer to another and the database file is still available in the projectCan test the application without altering the original data file

Page 8: Chapter 3 Windows Database Applications - … · Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good

8

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-22

Creating a Windows Database Application in a Grid

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-23

The DataSet Designer

After you add a new data source, a file with the extension .xsd is added to the files in the Solution ExplorerDouble-click to open the DataSet DesignerUsed to view and modify the definition of a DataSet

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-24

Preview Data

In the DataSet Designer, right-click the table name and select Preview DataClick the Preview button in the Preview Data dialog box

Page 9: Chapter 3 Windows Database Applications - … · Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good

9

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-25

Displaying Data in Individual Fields

In the Data Sources window, select the table nameDrop down the list of choicesSelect Details, rather than the default DataGridView

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-26

Selecting the Control Type for Details View

Choose the type of control for each database field or change defaultsMake the selection before dragging the table to the formSelect a database field, drop down the list for an individual field and make a selection

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-27

Populating Combo Boxes with Data

Set the DataSource propertyConnects to the DataSet

Set the DisplayMemberproperty

Selects the field to display in the list

Automatically fill a list by binding it to a field in a DataSetSet the combo box data bindings to not update the DataSet when the combo box selection changes

Page 10: Chapter 3 Windows Database Applications - … · Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good

10

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-28

Adding an Expression to Concatenate Fields

Used when you need information from a database in a format other than the way it is stored, such as a calculated expressionDouble-click the DataSet’s filename in the Solution Explorer –OR-Use the Data Sources window and select Edit DataSet with Designer

SQL Server uses a plus sign for concatenation rather than the ampersand used by VB and single quotes rather than double quotes for literalslname + ′, ′ + fname

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-29

Sorting Data for the ListBox

Sorting must be done on the data either using the binding source or in the SQL

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-30

Modifying the SQL Select Statement

When a DataSet is created from a database the resulting table data are produced by a query written in SQLEach table in the DataSet has an associated TableAdapter component with a Fill methodFill method retrieves the data from the data source

View and modify the SQL statement directly or by using the Query Builder (recommended practice)

Me.EmployeeTableAdapter.Fill(Me.PubsDataSet.employee)

Page 11: Chapter 3 Windows Database Applications - … · Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good

11

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-31

Query Builder

Creates the SQL statement to match the selection criteria that is entered, can be used to test a created SQL statement or add an expression field

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-32

Eliminating Unnecessary SQL Queries

When a TableAdapter is generated, VS designer automatically generates the SQL SELECT statement for retrieving dataThe designer also generates SQL INSERT, DELETE, and UPDATE statements

For programs that only display data, the extra statements serve no purpose and should be eliminatedTo delete extra code for updates, display the DataSet in the designer and click on the TableAdapter nameSelect either Configure from the Data menu or right-click on the Table Adapter and select Configure from the context menu to display the TableAdapter Configuration Wizard

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-33

TableAdapter Configuration Wizard

Click the Advanced Options button to display the dialog box

Page 12: Chapter 3 Windows Database Applications - … · Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good

12

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-34

Creating a Stored Procedure in VS IDE

Use the Server Explorer View and Add connectionsServer Explorer shows all connections that are defined with available objects in each database

Cannot drag tables and fields as is possible from the Data Sources window

To create a new stored procedures, Server Explorer must be usedTo create a new stored procedure, right-click on the Stored Procedures folder for a database and select Add New Stored Procedure

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-35

Server Explorer

Expand each of the nodes to see tables, views and stored procedures that exist

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-36

Retrieving Data by Using a Stored Procedure

Adding a grid or details for a form from a stored procedure is almost the same as using a tableFrom the DataSources window, select Add a New Data Source to display the Data Source Configuration WizardFollow the steps for any connection but expand the Stored Procedures items under Database objects and check the procedure that you createdThe name following the CREATE PROCEDURE clause appears on the list

Page 13: Chapter 3 Windows Database Applications - … · Windows Database Applications In this chapter, you learn to access and display database data on a Windows form. You will follow good

13

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-37

Multiple Tier Projects

Separate database access from the user interfaceCreate a data component as a separate tier

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-38

Coding the Form’s Database Objects

Code must be written to instantiate the data-tier component, retrieve the DataSet, and bind the form’s controls

′ Create an instance of the data-tier component.Dim employeeData As New PubsEmployeeData

′ Retrieve the dataset from the data tier.Dim aDataSet As PubsDataSetaDataSet = employeeData.getEmployeeDataset()

McGraw-Hill © 2007 The McGraw-Hill Companies, Inc. All rights reserved.3-39

Binding Data Fields toForm Controls

DataSet is created at run timeBind the fields from the DataSet to form controls after retrieving the DataSetBest way to bind form controls is to use the BindingSource objectDeclare and instantiate a new BindingSource object in code and set its DataSource and Data Member propertiesIf using a stored procedure specify the name of the stored procedure in place of the table name