Download presentation
Presentation is loading. Please wait.
1
© 2013, Mike Murach & Associates, Inc.
This chapter shows how to get data from a data source. The book is using the SQL Server express Local DB program. Your queries will work in SQL server, you just need to change the connection string to indicate the new data source. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
2
© 2013, Mike Murach & Associates, Inc.
Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
3
© 2013, Mike Murach & Associates, Inc.
Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
4
© 2013, Mike Murach & Associates, Inc.
The DataSources tab near the Toolbox tab shows the data sources which are available to our project. You can add a new data source using the link in the data sources window. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
5
© 2013, Mike Murach & Associates, Inc.
Here we have added the MMABooks database. We have selected just the products table so we see the 3 properties of a product underneath the drop down. This visual interface to our data is really convenient and makes it easier to create good applications. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
6
Data Source Configuration Wizard – Step 1
Add New Data Source 1. Data sources window 2. Button at top of Data sources window 3. Add new data source-Project menu 4. Project Add Existing Item Here is how to add a data source to a project. After you click the Add New Data Source this Data Source Configuration Wizard appears. We are connecting to a database. Services are internet-based data and objects would be business objects. The point is that we can connect to several different data sources. There are 4 ways to add a new data source to your program. Use the data sources window and click the Add New Data Source link Click the + sign at the top of the data sources window. Use the project menu to add a new data source to your project. Add an existing SQL server or Access databasto your You need to install the SQL server express database system on your PC. This allows you to access the databases like products and customer. Install SQL Server Express on your PC Download from Microsoft Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
7
Data Source Configuration Wizard – Step 2
When you choose the database option and click next you choose the database model. The book is using the dataset model. The Entity Data Model is described in Visual studio help. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
8
Data Source Configuration Wizard – Step 3
Now we create the connection to the data source. The book example has an MMABooks database in the Datbase folder included with the example program. You can see the path to the data source in the connection string window at the bottom of the screen. The system will ask you if you want to include the file in your project. This will copy the database into the output directory of the project. You will be working on a copy of the database, not the original version. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
9
© 2013, Mike Murach & Associates, Inc.
Add the connection by browsing for the database. Notice here that the book has a separate Database folder. Use Windows Authentication. This avoids the username and password requirement of the SQL Server Authentication system. You can test the connection to be sure the connection is correct. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
10
© 2013, Mike Murach & Associates, Inc.
The first time you make a data connection in your project you are prompted for the Data Source. Several common databases are shown like Access, Oragle and Microsoft SQL Server. The system will create the correct code for our chosen source. We choose Microsoft SQL Server Database File since we are using the SQL Server Express LocalDB. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
11
Data Source Configuration Wizard – Step 4
Your connection string will be saved in the application config file. Saving the connection sting in the default location lets all your table adapters use the same connection string. If you change the database name, you only have to change it in the app.config file, not throughout your program. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
12
© 2013, Mike Murach & Associates, Inc.
This is the XML code in the config file. It is pretty easy to read. The code begins with the connectionStrings key word. Then we add the name of our connection. Then we specify the connection itself. The database is inside the application so the string refers to the DataDirectory of the application. Finally we have the provider name – SqlClient. This is from the System.Data namespace Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
13
© 2013, Mike Murach & Associates, Inc.
Just like that we are connected to the database and see all the tables. We can expand the Products table and select the three properties we need. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
14
© 2013, Mike Murach & Associates, Inc.
The OnHandQuantity has a default value in the database. If we include OnHandQuantity in the dataset then we must assign a value to it. Otherwise the program puts a null in the quantity when we add a new record. The database is not accepting nulls so we get an exception at that point. If you include the OnHandQuantity, be sure to add code in your application to set a default value for it. Only include columns with default values if you need them in your application. If we are just adding products then we can use the default value. If we are updating inventory records then we need the OnHandQuantity and must handle it correctly to avoind exceptions. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
15
© 2013, Mike Murach & Associates, Inc.
We have completed the Data Source Wizard and the MMABooksDataSet appears in the data sources window. The products table, with our 3 columns is inside the dataset. The system creates an XML schema defining the data. This is in the solution explorer. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
16
© 2013, Mike Murach & Associates, Inc.
We drag the products table onto the form and we get a DataGridView control. The system has added the 3 columns to the control. We also have a navigation bar at the top of the form. We will be able to move forwards and backwards through the dataset. We also get add and delete icons. We have to write some of the code for those buttons, but they are included in the data grid view by default. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
17
© 2013, Mike Murach & Associates, Inc.
4 5 6 This is on the form itself Defines the toolbar Identifies the data source for our controls Access to tables in the project Provides read/write commands Writes data to the database 3 4 5 The system creates the data grid view control and it adds 5 controls to the system tray. These objects control all our data interactions. We get the toolbar from the BindingNavigator. It is helping us navigate through the bound data. Our data grid view, and other controls on forms, need a BindingSource to indicate where the data comes from. The dataset object gives access to the tables, views, stored procedures and functions in the project. The table adapter gives us the Read/Write commands to get the data from the database. The TableAdapterManager writes to the database from our project tables. Each step of the process has its own object. This makes it easier to see and manage the data access tools. 6 2 Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
18
© 2013, Mike Murach & Associates, Inc.
The data grid view is filled with the data when we run the application. We have scroll bars on the right side. The toolbar shows the count of records and our location. The navigation arrows move us through the records. The plus icon adds a row to the table. The delete button deletes the row we select. Be careful that you don’t delete data by mistake. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
19
Data Adapter Code – Created Automatically
The system creates this code when you create the data source and drag the data to the form. It automatically creates the DataGridView control and these two methods.The form load method uses the Fill method of the table adapter to fill the data set called products. The productsBindingNavigatorSaveItem_Click method handles the updates to our database. We can call the form validation method, but as the book points out, this does not work well with the binding navigator toolbar. The EndEdit applies any changes to the data set, not the database. The table adapter’s update all method finally saves the data into the original database. The adapter checks each row of the dataset for changes. It then creates the SQL insert, update and delete statements for the changed rows. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
20
© 2013, Mike Murach & Associates, Inc.
Here is the syntax for the table adapter FILL method. We have to provide the data set and its table name. This allows the adapter to fill that table. The update all method is from the tableAdapterManager. We just specify the dataset, not the table. The adapter will handle all the changes to the data. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
21
© 2013, Mike Murach & Associates, Inc.
We can also display the data in controls on the form. There is a drop down list for the table. The default choice is DataGridView, but we can also view the details. This will show the data in separate controls on the form. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
22
© 2013, Mike Murach & Associates, Inc.
We can also change the type of control that displays our data. There is a drop down list for each field in the table. The default is a text box, but we might want a list in a combo box. Or we put the information into a label so it cannot be edited. If we are just retrieving data, like looking up your grades, we can show that in a label. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
23
© 2013, Mike Murach & Associates, Inc.
Data Bindings We changed our table view to details. Drag the table onto the form. Now the data is displayed in individual controls on the form. The system also created our data access tools just like it did for the DataGridView. Just 1 row is displayed at a time in this layout. The controls are bound to only 1 field so this is called simple data binding. The textboxes show data from the table so they each have a data binding, a field they are showing. The text property in the data bindings is set to CustomerID in the first textbox. There is a small down arrow in the text property where you can see the columns bound to that control. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
24
© 2013, Mike Murach & Associates, Inc.
We can rearrange the controls and change properties to our liking. This is the Customer Maintenance form. We don’t want users to change the CustomerID so we make that read-only. City, State and Zip look nicer placed on the same row. So we drag the textboxes into position. This makes a more readable interface and it required almost no work. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
25
© 2013, Mike Murach & Associates, Inc.
This code fills the data set on form load. It handles the click event of the save item. This is the same code we had for products, except our table name is Customers now. This is very standard code. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
26
Handling data exceptions
Sources of exceptions Data provider ADO.NET DataGridView We should include exception handling in our programs. There are 3 sources of exceptions. Our data provider, the database server, might not be available, broken or off line. This will cause an exception to be thrown from the Data Provider. ADO.NET has its own collection of exceptions and we will look at those in a few slides. The DataGridView will raise exceptions when we try to fill it. Each of these classes has their own exceptions. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
27
© 2013, Mike Murach & Associates, Inc.
These are the .NET data providers which can throw exceptions. Each type of provider has its own exception names. The exception classes start with the name of the provider, SQL, Oracle, ODBC and OleDB. This allows each provider to have its own explicit exceptions, not just generic ones. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
28
© 2013, Mike Murach & Associates, Inc.
We looked at exceptions in chapter 7. Exceptions share several properties, like message and the GetType method. We can use these to build informative messages for our users. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
29
© 2013, Mike Murach & Associates, Inc.
This is an enhanced version of our form load and dataset fill code. We put the fill call inside a try catch block. Then we catch an SQLException because we have an SQLServer data provider. We show a message box that gives the user the exception number and the message. Then we show the type of the exception. We can have multiple exceptions at the same time. These are stored in a collection and you can show each of the exceptions to the user. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
30
© 2013, Mike Murach & Associates, Inc.
ADO.NET throws some common exceptions we might need to handle. Concurrency exception occurs when zero rows are affected by the insert, update or delete operations. DataException is the general exception thrown by the ADO.NET class. We can have constraints in our database and datatables. The ConstraintException is thrown if we violate a constraint in our database. Some columns in the database might not allow null values. The NoNullAllowedException is thrown if we try to store a null in one of those columns. This is why we need to carefully initialize variables and our data to valid values. We know exceptions have a message which we can display. The exception also has a GetType method. We can use the Type of the exception in our exception handling. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
31
© 2013, Mike Murach & Associates, Inc.
Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
32
ADO.NET exception handling code
This is part of the exception handling for the save item method. The EndEdit and UpdateAll calls are inside the try block. Then we catch our exceptions. A concurrency exception shows a message and then table adapter fills the dataset with new data. No rows were changed, but we need to refill the table. A DataException is the general exception. We use the CancelEdit method to cancel the current edit operation. Finally we catch any exceptions thrown by the SQL Client class. SQLClient Exception, not ADO.NET Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
33
© 2013, Mike Murach & Associates, Inc.
DataGridControls can also throw exceptions. It can detect some data entry errors before you save the data. This can prevent data problems in the database itself. If there are inconsistencies in the data, inivalid or missing, the control throws a DataError. The error event class contains important properties. The Exception itself has a message property we can put in messages. We can also get the specific row and column where the exception occurred. We can help the user see exactly where the problem occurred. This is better than just saying there is something wrong with the data. Help your users wheneve you can. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
34
© 2013, Mike Murach & Associates, Inc.
The DataGridView will raise the DataError event if there is an error in our data before it is saved. This means we need a method to handle this error event. The method receives the Event Args, e, for the error. This gives us an object which has RowIndex, ColumnIndex and EXCEPTION. This code gets the row index from E and adds 1. Rows are numbered 0 to n, so row 1 is index 0, but we need to add 1 to the row index to get the correct row number in our data. Then we can show the message of the exception to the user. We would return the user to the row in question so they could fix the data before saving the record. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
35
© 2013, Mike Murach & Associates, Inc.
The system creates a schema for our dataset. It is the XSD file with the database icon in the solution explorer. This shows the structure of our dataset, the results of our query. The key field is identified by a key, just like other databases. The Table Adapter and its commands are also in the schems. The default method for the table adapter is Fill which is displayed under the table adapter. Selecting the table adapter opens its properties window. We can create or edit the Delete, Insert, Select commands. There is a property for insert, delete, select commands. Expand those and you can see the command text. Click the ellipses for the command text and the query builder will appear. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
36
© 2013, Mike Murach & Associates, Inc.
Diagram pane Grid pane SQL pane The query builder is a very useful tool. It allows you to construct SQL queries using a point and click ineterface. You don’t need to know how to write SQL. The builder will do it for you. There are 4 sections to this screen. The diagram shows the table for our dataset, the Customers. We can add other tables to the SELECT query by right clicking in the diagram pane and choosing Add Table. The columns in the query are displayed in the Grid pane. We can adjust some parameters of the query like sorting in the grid pane. The SQL pane shows the SQL command that is built for you. This can help you understand your query and maybe correct it if you are not getting the results you expect. Clicking Execute Query will show the results in the Results pane. The dialog can be resized to see more of the results. Results pane Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
37
© 2013, Mike Murach & Associates, Inc.
Copy text from SQL pane. Paste into database engine or save to view later. SELECT CustomerID, Name, Address, City, State, ZipCode FROM Customers The SQL string can be edited or copied from the SQL pane. You could paste this into a database’s command window. This lets you see how your query affects the table directly. Sometimes you can’t detect your SQL errors until you run it on a real database. The data adapters can get in the way of understanding your query. The results pane shows the data from your query. You can expand the dialog to see more of your results. The book shows a larger table of results that we don’t have in Visual Studio 2015. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
38
© 2013, Mike Murach & Associates, Inc.
Here are some example SQL statements. We have a simple SELECT statement that lists the columns to retrieve and the table to get them FROM. The INSERT command specifies the table, customers, and the columns in the table. We then list the values of those columns. The values must be in the same order as the columns. The statement below the red line is a separate query that will refresh the dataset. We would do this after making changes to the database to ensure our dataset had the latest information. SCOPE_IDENTITY is a SQL server function that returns the last identity value. So you get the customer ID for the row you were working with. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
39
© 2013, Mike Murach & Associates, Inc.
parameter @variable_name Refers to current value of variable The UPDATE statement is using optimistic concurrenct to update the row. The where clause is controlling the update. The at signs create parameters we can use in our SQL statements. It lets us use the current value of a variable in a query. So is assigning the current value to the variable name. Later we compare this name to value. All 6 parts of the WHERE clause must be true before we do the update. The dataset column values are on the left and the original row data is on the right of the equals sign. I am checking that none of the values have changed in the database. If my values match then I will update the row. The SELECT statement is reloading the new row into the dataset. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
40
© 2013, Mike Murach & Associates, Inc.
The DELETE statement uses the WHERE clause to ensure it is deleting the correct row. We are saying to delete from the customers table the row which has the correct CustomerID, Name, Address, City, State, Zip. If any of these are changed we won’t do the delete. Murach's C# 2012, C18 © 2013, Mike Murach & Associates, Inc.
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.