How to work with data sources and datasets

Similar documents
ADO.NET 2.0. database programming with

How to use data sources with databases (part 1)

FOR 240 Homework Assignment 4 Using DBGridView and Other VB Controls to Manipulate Database Introduction to Computing in Natural Resources

Chapter 3. Windows Database Applications The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies. Objectives (1 of 2)

Windows Database Applications

CSC 330 Object-Oriented

Programming with ADO.NET

VS2010 C# Programming - DB intro 1

Building Datacentric Applications

Chapter 10. Database Applications The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Windows Database Updates

Introduction to using Visual Studio 2010 to build data-aware applications

CIS 209 Final Exam. 1. A Public Property procedure creates a property that is visible to any application that contains an instance of the class.

Supporting Non-Standard Development Configurations

Volume CREATIVE DATA TECHNOLOGIES, INC. DATALAYER.NET. Getting Started Guide

About the Authors Introduction p. 1 Exploring Application Architectures p. 9 Introduction p. 9 Choosing the "Right" Architecture p.

Advanced Programming C# Lecture 5. dr inż. Małgorzata Janik

Chapter 4. Windows Database Using Related Tables The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Lesson 6: Using XML Queries

IOS Plus Trade - Web Services Version 4 Walkthrough

IRESS Depth - Web Services Version 4 Walkthrough Visual Basic 2008 sample to retrieve IRESS Depth information

Data Binding. Data Binding

QDABRA DBXL S XML RENDERING SERVICE CONFIGURATION

Learning VB.Net. Tutorial 19 Classes and Inheritance

Chapter 10 Databases

ComponentOne. DataObjects for.net

Microsoft Access 2010

Microsoft Access 2013

Microsoft Access 2013

Setting Synchronization Direction

Form Adapter Example. DRAFT Document ID : Form_Adapter.PDF Author : Michele Harris Version : 1.1 Date :

How to Validate DataGridView Input

Else. End If End Sub End Class. PDF created with pdffactory trial version

.NET and DB2 united with IBM DB2.NET Data Provider Objectives :.NET ADO.NET DB2 and ADO.NET DB2 - ADO.NET applications

Connection Example. Document ID : Connection_Example.PDF Author : Michele Harris Version : 1.1 Date :

Enforce Referential. dialog box, click to mark the. Enforce Referential. Integrity, Cascade Update Related Fields, and. Cascade Delete Related

1. A Web Form created in Visual Basic can only be displayed in Internet Explorer. True False

ComponentOne. DataObjects for.net

Chapter 3 How to use HTML5 and CSS3 with ASP.NET applications

Oracle Rdb Developer Tools for Visual Studio Developer s Guide, Release Copyright 2011 Oracle Corporation Corporation. All rights reserved.

Database Tutorials

Hands-On Lab. Lab: Client Object Model. Lab version: Last updated: 2/23/2011

1. Create your First VB.Net Program Hello World

DO NOT COPY AMIT PHOTOSTUDIO

Object Oriented Programming Using Visual C# 2012-Level 2

Oracle SQL. murach s. and PL/SQL TRAINING & REFERENCE. (Chapter 2)

6.1 Understand Relational Database Management Systems

Table of Contents DATA MANAGEMENT TOOLS 4. IMPORT WIZARD 6 Setting Import File Format (Step 1) 7 Setting Source File Name (Step 2) 8

Oracle Rdb Developer Tools for Visual Studio Developer's Guide Release June 2015

Visual Basic 2008 Anne Boehm

Sage Estimating (SQL) v17.12

C16 Visual Basic Net Programming

COMM 391. Objectives. Introduction to Microsoft Access. What is in an Access database file? Introduction to Microsoft Access 2010

APEX Times Ten Berichte. Tuning DB-Browser Datenmodellierung Schema Copy & Compare Data Grids. Extension Exchange.

Revision for Final Examination (Second Semester) Grade 9

Create a Windows Application that Reads- Writes PI Data via PI OLEDB. Page 1

ADO.NET Using Visual Basic 2005 Table of Contents

Interacting with External Applications

Contents. Chapter 1 Introducing ADO.NET...1. Acknowledgments...xiii. About the Authors...xv. Introduction...xix

Object Oriented Programming Using Visual C# 2012-Level 2

Working with Data in ASP.NET 2.0 :: Using Existing Stored Procedures for the Typed DataSet s TableAdapters Introduction

To enter the number in decimals Label 1 To show total. Text:...

UNIT V - ADO.NET Database Programming with ADO.NET- Data Presentation Using the DataGridView Control- DataGridView- Updating the Original Database.

Test Bank Database Processing Fundamentals Designand Implementation 14th Edition Kroenke

Tutorial 1. Creating a Database

VB. Microsoft. MS.NET Framework 3.5 ADO.NET Application Development

Exploring Microsoft Office Access Chapter 2: Relational Databases and Multi-Table Queries

Database Application Development Oracle PL/SQL, part 2. CS430/630 Lecture 18b

Accessing Databases 7/6/2017 EC512 1

Melon, Inc. Melon Components Starter Kit

Dynamically build connection objects for Microsoft Access databases in SQL Server Integration Services SSIS

Lecture 10 OOP and VB.Net

DATA MIRROR FOR PT USER S GUIDE. Multiware, Inc. Oct 9, 2012 *Changes are in red font*

Access Intermediate

Connect Databases to AutoCAD with dbconnect Nate Bartley Test Development Engineer autodesk, inc.

Crystal Reports. Overview. Contents. Differences between the Database menu in Crystal Reports 8.5 and 9

Programming Logic -Intermediate

Database Tutorials

IMS1906: Business Software Fundamentals Tutorial exercises Week 5: Variables and Constants

Access Intermediate

Microsoft Visual C# 2005: Developing Applications Table of Contents

Database Applications

How to design a database

Learning VB.Net. Tutorial 17 Classes

If this is the first time you have run SSMS, I recommend setting up the startup options so that the environment is set up the way you want it.

"!#... )*! "!# )+, -./ 01 $

SQL Server Reporting Services (SSRS) is one of SQL Server 2008 s

Tutorial 03 understanding controls : buttons, text boxes

What s New in Jet Reports 2010 R2

PL/SQL Developer 7.0 New Features. December 2005

2.1 Read and Write XML Data. 2.2 Distinguish Between DataSet and DataReader Objects. 2.3 Call a Service from a Web Page

Complete Quick Reference Summary

Visual Studio.NET for AutoCAD Programmers

COPYRIGHTED MATERIAL. Taking Web Services for a Test Drive. Chapter 1. What s a Web Service?

A201 Object Oriented Programming with Visual Basic.Net

Tutorial 2. Building a Database and Defining Table Relationships

ARPEGGIO Data Access Frequently Asked Questions

Introduction to relational databases and MySQL

University of North Dakota PeopleSoft Finance Tip Sheets. Utilizing the Query Download Feature

Transcription:

Chapter 14 How to work with data sources and datasets Objectives Applied Use a data source to get the data that an application requires. Use a DataGridView control to present the data that s retrieved by a data source. Use other controls like text boxes to present the data that s retrieved by a data source. Write the Visual Basic code for handling any data errors that result from the use of the data source or the controls that are bound to it. Use the Dataset Designer to (1) view the schema for the dataset of a data source, (2) modify a query using the Query Builder, (3) preview the data for a query, or (4) review the SQL statements that are generated for a data source. Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 1 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 2 Objectives (continued) Knowledge Describe the use of a connection string in an app.config file. Describe the use of the Fill and UpdateAll methods of the TableAdapter object. Describe the use of the EndEdit method of the BindingSource object. Describe the two categories of data errors that can occur when you run an application that uses a data source. Describe the use of the DataError event for a DataGridView control. In general terms, describe the way the SQL statements that are generated for a data source (1) prevent concurrency errors, and (2) refresh a dataset when the database generates the keys for new rows. An empty Data Sources window Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 3 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 4 A Data Sources window after a data source has been added The first step of the Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 5 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 6 1

How to start the Click on the Add New Data Source link that s available from the Data Sources window when a project doesn t contain any data sources. Click on the Add New Data Source button at the top of the Data Sources window. Select the Add New Data Source command from Visual Studio s Dt Data menu. Add a SQL Server (.mdf) or Access (.mdb) data file to the project using the Project Add Existing Item command. Then, the wizard will let you choose the database objects you want to include. How to choose a data source type To get your data from a database, select the Database option. This option lets you create applications like the ones described in this chapter. To get your data from a web service, select the Web Service option. This option lets you browse the web to select a web service that will supply data to your application. To get your data from a business object, select the Object option. Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 7 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 8 The second step of the The Add Connection and Change Data Source dialog boxes Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 9 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 10 In the Express Edition The Change Data Source dialog box provides only three options: Microsoft Access Database File, Microsoft SQL Server Compact 3.5 (the default), and Microsoft SQL Server Database File. The Add Connection dialog box is simpler, and it includes a Database File Name text box that you use to specify the database. The third step of the Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 11 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 12 2

The information that s stored in the app.config file <connectionstrings> <add name= "ProductMaintenance.My.MySettings.MMABooksConnectionString" connectionstring="data Source=localhost\sqlexpress; Initial Catalog=MMABooks; Integrated Security=True" providername="system.data.sqlclient" /> </connectionstrings> The last step of the Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 13 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 14 How to work with columns that have default values If a column in a database has a default value, that value isn t included in the column definition in the dataset. Because of that, you may want to omit columns with default values from the dataset unless they re needed by the application. Then, when a row is added to the table, the default value is taken from the database. If you include a column that s t defined d with a default value, you must provide a value for that column whenever a row is added to the dataset. One way to do that is to let the user enter a value. Another way is to display the Dataset Designer and use the Properties window for the column to set the DefaultValue property. A project with a dataset defined by a data source Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 15 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 16 A form after the Products table has been dragged onto it The controls and objects that are created when you drag a data source to a form Control/object DataGridView control Displays the data from the data source in a grid. BindingNavigator control Defines the toolbar that can be used to navigate, add, update, and delete rows in the DataGridView control. BindingSource object Identifies the data source that the controls on the form are bound to and provides functionality for working with the data source. DataSet object Provides access to all of the tables, views, stored procedures, and functions that are available to the project. Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 17 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 18 3

The controls and objects that are created when you drag a data source to a form (continued) Control/object TableAdapter object Provides the commands that are used to read and write data to and from the specified table in the database. TableAdapterManager object Provides for writing data in related tables to the database while maintaining referential integrity. The user interface for the Product Maintenance application Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 19 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 20 The code that s generated by Visual Studio Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 'TODO: This line of code loads data into the ''MMABooksDataSet.Products' table. 'You can move, or remove it, as needed. Me.ProductsTableAdapter.Fill( _ Me.MMABooksDataSet.Products) Private Sub ProductsBindingNavigatorSaveItem_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles ProductsBindingNavigatorSaveItem.Click Me.Validate() Me.ProductsBindingSource.EndEdit() Me.TableAdapterManager.UpdateAll(Me.MMABooksDataSet) The syntax of the Fill method TableAdapter.Fill(DataSet.TableName) The syntax of the UpdateAll method TableAdapterManager.UpdateAll(DataSet) Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 21 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 22 How to change the default control for a data table How to change the default control for a column in a data table Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 23 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 24 4

A form after the Customers table has been dragged onto it The user interface for the Customer Maintenance application Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 25 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 26 The code for the Customer Maintenance application Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 'TODO: This line of code loads data into the ''MMABooksDataSet.Customers' table. 'You can move, or remove it, as needed. Me.CustomersTableAdapter.Fill( _ Me.MMABooksDataSet.Customers) Private Sub CustomersBindingNavigatorSaveItem_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles CustomersBindingNavigatorSaveItem.Click Me.Validate() Me.CustomersBindingSource.EndEdit() Me.TableAdapterManager.UpdateAll(Me.MMABooksDataSet) End Class.NET data provider exception classes Name Thrown if a server error occurs SqlException When accessing a SQL Server database. OracleException When accessing an Oracle database. OdbcException When accessing an ODBC database. OleDbException When accessing an OLE DB database. Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 27 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 28 Common members of the.net data provider exception classes Property Number An error number that identifies the type of error. Message A message that describes the error. Source The name of the provider that generated the error. Errors Method GetType() A collection of error objects that contain information about the errors that occurred during a database operation. Gets the type of the current exception. Code that catches a SQL exception Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load Try Me.CustomersTableAdapter.Fill( _ Me.MMABooksDataSet.Customers) Catch ex As SqlException MessageBox.Show("Database error # " & ex.number _ & ": " & ex.message, ex.gettype.tostring) End Try Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 29 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 30 5

Common ADO.NET exception classes Class DBConcurrencyException The exception that s thrown if the number of rows affected by an insert, update, or delete operation is zero. DataException The general exception that s thrown when an ADO.NET error occurs. ConstraintException The exception that s thrown if an operation violates a constraint. This is a subclass of the DataException class. NoNullAllowedException The exception that s thrown when an add or update operation attempts to save a null value in a column that doesn t allow nulls. This is a subclass of the DataException class. Common members of the ADO.NET classes Property Message A message that describes the exception. Method GetType() Gets the type of the current exception. Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 31 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 32 Code that handles ADO.NET errors Try Me.CustomersBindingSource.EndEdit() Me.TableAdapterManager.UpdateAll(Me.MMABooksDataSet) Catch ex As DBConcurrencyException MessageBox.Show("A concurrency error occurred. " _ & "Some rows were not updated.", _ "Concurrency Error") Me.CustomersTableAdapter.Fill( _ Me.MMABooksDataSet.Customers) Catch ex As DataException MessageBox.Show(ex.Message, ex.gettype.tostring) CustomersBindingSource.CancelEdit() Catch ex As SqlException MessageBox.Show("Database error # " & ex.number _ & ": " & ex.message, ex.gettype.tostring) End Try An event of the DataGridView control Event DataError Raised when the DataGridView control detects a data error such as a value that isn t in the correct format or a null value where a null value isn t valid. Three properties of the DataGridViewDataErrorEventArgs class Property Exception RowIndex ColumnIndex The exception that was thrown as a result of the error. You can use the Message property of this object to get additional information about the exception. The index for the row where the error occurred. The index for the column where the error occurred. Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 33 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 34 Code that handles a data error for a DataGridView control Private Sub ProductsDataGridView_DataError( _ ByVal sender As System.Object, _ ByVal e As _ System.Windows.Forms.DataGridViewDataErrorEventArgs) _ Handles ProductsDataGridView.DataError Dim row As Integer = e.rowindex + 1 Dim errormessage As String = _ "A data error occurred." & vbcrlf _ & "Row: " & row & vbcrlf _ & "Error: " & e.exception.message MessageBox.Show(errorMessage, "Data Error") The schema displayed in the Dataset Designer Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 35 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 36 6

The Query Builder The Preview Data dialog box Diagram Grid SQL Results Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 37 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 38 SQL that retrieves customer rows SELECT FROM CustomerID, Name, Address, City, State, ZipCode Customers SQL that inserts a customer row and refreshes the dataset INSERT INTO Customers (Name, Address, City, State, ZipCode) VALUES (@Name, @Address, @City, @State, t @ZipCode); SELECT FROM WHERE CustomerID, Name, Address, City, State, ZipCode Customers (CustomerID = SCOPE_IDENTITY()) SQL that updates a customer row and refreshes the dataset UPDATE Customers SET Name = @Name, Address = @Address, City = @City, State = @State, ZipCode = @ZipCode WHERE ( (CustomerID = @Original_CustomerID) AND (Name = @Original_Name) AND (Address = @Original_Address) AND (City = @Original_City) AND (State = @Original_State) AND (ZipCode = @Original_ZipCode) ); SELECT FROM WHERE CustomerID, Name, Address, City, State, ZipCode Customers (CustomerID = @CustomerID) Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 39 Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 40 SQL that deletes a customer row DELETE FROM Customers WHERE (CustomerID = @Original_CustomerID) AND (Name = @Original_Name) AND (Address = @Original_Address) AND (City = @Original_City) AND (State = @Original_State) AND (ZipCode = @Original_ZipCode) Murach s Visual Basic 2008, C14 2008, Mike Murach & Associates, Inc. Slide 41 7