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