Chapter 3 Windows Database Applications McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved.
Objectives - 1 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 McGraw-Hill 3-2
Objectives - 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 TableAdapter objects in code and write the code to bind data to form controls McGraw-Hill 3-3
Visual Studio and Database Applications Professional VB programmers spend the majority of their time on applications involving databases The managed providers included in the.net Framework are Microsoft Access Database File Microsoft ODBC Data Source Microsoft SQL Server Compact 3.5 Microsoft SQL Server Database File Oracle Database (other database formats) McGraw-Hill 3-4
ADO.NET - 1 Latest version of ADO.NET is 3.5 Allows programmers to use a standard set of objects to refer to any data source.net approach uses disconnected DataSets with common data types from multiple sources Integrated with XML Well-written multitier applications that use disconnected DataSets provide for flexibility and scalability McGraw-Hill 3-5
ADO.NET - 2 Flexible applications can adapt to Changes in the database Changes to the user interface Scalable applications can handle increases in Number of users Number of servers McGraw-Hill 3-6
Accessing Data in the.net Framework Terminology for working with data Data sources Data designers Datasets Binding sources Table adapters Other standard terms for data elements McGraw-Hill 3-7
Database Terminology A data table consists of rows and columns Each row represents the data for one item, person or transaction and is called a record Each column represents a different element of data and is called a field A primary key field (or combination of fields) uniquely identifies each record McGraw-Hill 3-8
Data Sources An application obtains data from a data source Data sources can be created from a largescale database, a local database file, a Web service, or other types of objects A typed DataSet is added when a data source is created from a database Each typed DataSet has a schema, which describes the fields and their data types McGraw-Hill 3-9
DataSet Objects A DataSet object holds a copy of the data in memory, disconnected from the data source A temporary cache rather than the actual database data A DataSet object can hold one or more tables A relational database contains multiple tables and has relationships between tables McGraw-Hill 3-10
The DataSet Object Model - 1 Each DataSet object contains a DataTable collection made up of individual DataTable objects DataTable object has DataRow and DataColumn collections Single DataRow holds data for one record DataRow object maintains original and any changed values Information used to determine which rows have changed during execution McGraw-Hill 3-11
The DataSet Object Model - 2 A DataRelation object stores information about related tables Which columns contain primary and foreign keys that link the tables Constraints collection (belongs to DataTable object) holds Unique constraints (Primary key) Enforce the requirement that values in the specified field be unique ForeignKey constraints Requires any foreign key value that appears in a secondary table match a primary key value in the primary table McGraw-Hill 3-12
The DataSet Object Model - 3 McGraw-Hill 3-13
TableAdapters A TableAdapter 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 Handles writing any changes back in the data source Can hold multiple queries Data is retrieved by calling a specific query or getting all of the data for the table Visual designers in the VS IDE automatically generate Table Adapters when a typed DataSet is added McGraw-Hill 3-14
BindingSource Objects Facilitates binding the controls on a Windows form to the data source Handles navigation, sorting, filtering and updating of data Keeps all of the form s controls displaying data from the same record (currency) McGraw-Hill 3-15
XML Data - 1 XML is generated automatically Data stored in XML is all text, identified by tags, similar to HTML XML files can be edited by any text editor Tags identify fields by name Specs found for XML at http://www.w3.org/xml McGraw-Hill 3-16
XML Data - 2 Each typed DataSet has a schema Defines the fields, data types, and any constraints ADO.NET validates the data against the schema and checks for constraint violations XML data offers programming advantages Schema provides for strong data typing XML data treated as objects Allows IntelliSense feature to provide information ADO.NET executes faster than ADO McGraw-Hill 3-17
Visual Studio IDE Provides tools to help with database applications Data Sources window Set up data sources for an application Server Explorer (Database Explorer in Express Edition) McGraw-Hill 3-18
The Data Sources Window - 1 Provides easy way to set up an application s data sources Set up the data source Add grids or individual fields by dragging a table or fields from the Data Sources window to the form Drop a field from the Data Sources window onto a control Displays database data in the control Causes data binding to be set up automatically McGraw-Hill 3-19
The Data Sources Window - 2 When tables or fields are dragged to a form An.xsd file with the schema is added to the Solution Explorer window DataSet, BindingSource, TableAdapter, and BindingNavigator objects are added to the component tray Add and view a project s DataSets Provides access to the DataSet Designer Visually displays the DataSets and data table relationships McGraw-Hill 3-20
Creating a Database Application Microsoft supports several products for designing and maintaining database files SQL Server Access SQL Server 2008 Express Edition Used for exercises in textbook McGraw-Hill 3-21
Local Database Files Visual Studio offers an option to place a copy of the database file inside the project Has advantages and disadvantages Can be used for development and testing Can move the project from one folder or computer to another and the database file is still available in the project Can test the application without altering the original data file McGraw-Hill 3-22
Creating a Windows Database Application McGraw-Hill 3-23
The DataSet Designer After a new data source is added, a file with the extension.xsd is added to the files in the Solution Explorer Double-click to open the DataSet Designer Used to view and modify the definition of a DataSet McGraw-Hill 3-24
View the Designer s Code Display the code in the DatasetName.Designer.vb file Place a breakpoint in the program on the line of code containing the Fill method Run the program and step into the code McGraw-Hill 3-25
Displaying Data in Individual Fields In the Data Sources window, select the table name Drop down the list of choices Select Details or the default DataGridView McGraw-Hill 3-26
Selecting the Control Type for Details View Choose the type of control for each database field or change defaults The selection must be made before dragging the table to the form To change the control type for a field, select the database field in the Data Sources window Drop down the list for an individual field and make a selection McGraw-Hill 3-27
Setting the Captions for Database Fields VS database design tools are smart Fields named with camel or Pascal casing are separated to make meaningful captions i.e. EmployeeNumber has a caption of Employee Number When the designer cannot parse a field name Change field captions in the DataSet Designer McGraw-Hill 3-28
Formatting Bound Data - 1 DateTimePicker control Long date format is default Change to a different date format by setting the Format property of the control TextBox Select the text box, scroll to the top of the Properties window Choose DataBindings and Advanced Click ellipsis button and display the Formatting and Advanced Binding dialog box Select Format type McGraw-Hill 3-29
Formatting Bound Data - 2 DataGridView Choose cell type and formatting for individual cells in the Edit Columns dialog box Select Edit Columns from the grid s smart tag Use the ColumnType property under the Design category To change the display format, scroll to the Appearance category and click on the build button for DefaultCellStyle Set properties in the Cell Style Builder dialog box Click the build button for Format to display the FormatStringDialog McGraw-Hill 3-30
Selecting a Record from a List Allow a user to select the desired record from a list List may hold a record s key field or some other value Based on user s selection, retrieve the corresponding record Display the detail data on the form McGraw-Hill 3-31
Populating Combo Boxes with Data Set the DataSource property Connects to the DataSet Set the DisplayMember property Specifies the field to display in the list Automatically fill a list by binding it to a field in a DataSet Set the combo box data bindings to not update the DataSet when the combo box selection changes McGraw-Hill 3-32
Adding an Expression to Concatenate Fields Used when information from a database is needed in a format other than the way it is stored For instance, a calculated expression or to concatenate first and last names Double-click the DataSet s filename (.xsd file) in the Solution Explorer or Add a new column (field) to the table Set the Expression property to specify what the new field contains Set the DisplayMember to the new column McGraw-Hill 3-33
Sorting the Data for the ListBox Sorting with the BindingSource BindingSource class automatically contains a Sort method Supply the field name for the sort process Modifying the SQL Select Statement View and modify the SQL statement directly or use the Query Builder McGraw-Hill 3-34
Using the Query Builder Add and remove tables Select fields to include Specify sort and selection criteria Query Builder creates SQL statement to match selection criteria entered Or type SQL statement manually and test using the Execute Query button McGraw-Hill 3-35
Eliminating Unnecessary SQL Queries When a TableAdapter is generated, VS designer automatically generates the SQL SELECT statement for retrieving data The designer also generates SQL INSERT, DELETE, and UPDATE statements For programs that only display data, the extra statements serve no purpose and should be eliminated To delete extra code for updates, display the DataSet in the designer and click on the TableAdapter name Select Configure from the Data menu The TableAdapter Configuration Wizard opens Click on the Advanced Options button Deselect unwanted options McGraw-Hill 3-36
Creating a Stored Procedure in the VS IDE Use the Server Explorer View and Add connections Server Explorer shows all connections that are defined with available objects in each database Cannot drag tables and fields from Server Explorer as is possible from the Data Sources window To create a new stored procedure, Server Explorer must be used Create a new stored procedure Right-click on the Stored Procedures folder for a database Select Add New Stored Procedure McGraw-Hill 3-37
Retrieving Data by Using a Stored Procedure Adding a grid or details to a form from a stored procedure is almost the same as using a table From the DataSources window, select Add a New Data Source to display the Data Source Configuration Wizard Follow the steps as for any connection but expand the Stored Procedures items under Database objects Check the procedure that was created The name following the CREATE PROCEDURE clause appears on the list McGraw-Hill 3-38
Multiple Tiers Separate database access from the user interface Create a data component as a separate tier McGraw-Hill 3-39
Coding the Form s Database Objects Write code to instantiate the data-tier component, retrieve the DataSet, and bind the form s controls Create an instance of the data-tier component. Dim APubsEmployeeData As New PubsEmployeeData Retrieve the dataset from the data tier. Dim APubsDataSet As PubsDataSet APubsDataSet = APubsEmployeeData.GetEmployeeDataset() McGraw-Hill 3-40
Binding Data Fields to Form Controls DataSet is created at run time Bind the fields from the DataSet to form controls after retrieving the DataSet Best way to bind form controls is to use the BindingSource object Declare and instantiate a new BindingSource object in code and set its DataSource and Data Member properties Bind form controls to the BindingSource object If using a stored procedure specify the name of the stored procedure in place of the table name McGraw-Hill 3-41