The DataSet Class Finding Tables

350 Do something with the data set. Dim dt As DataTable = ds.Tables.ItemLondonCustomers Dim rowCustomer As DataRow For Each rowCustomer In dt.Rows Console.WriteLinerowCustomer.ItemCompanyName Next The code in Ex am ple 8- 1 performs the following steps to obtain data from the database: 1. Opens a connection to the database using a SqlConnection object. 2. Instantiates an object of type SqlDataAdapter in preparation for filling a DataSet object. In Ex am ple 8- 1 , a SQL SELECT command string and a Connection object are passed to the SqlDataAdapter objects constructor. 3. Instantiates an object of type DataSet and fills it by calling the SqlDataAdapter objects Fill method.

8.5.1 The DataSet Class

The DataSet class encapsulates a set of tables and the relations between those tables. Figur e 8- 2 shows a class model diagram containing the DataSet and related classes. The DataSet is always completely disconnected from any data source. In fact, the DataSet has no knowledge of the source of its tables and relations. They may be dynamically created using methods on the DataSet, or they may be loaded from a data source. In the case of the SQL Server managed provider, a DataSet can be loaded from a SQL Server database using an SqlDataAdapter object. This is what was done in Ex am ple 8- 1 . Figure 8-2. A class model diagram for the DataSet and related classes 351 After a DataSet is loaded, its data can be changed, added to, or deleted, all without affecting the data source. Indeed, a database connection does not need to be maintained during these updates. When ready, the updates can be written back to the database by establishing a new connection and calling the SqlDataAdapter objects Update method. Examples of writing updates to a database are shown later in this chapter.Navigating the DataSet In this section youll learn how to find specific data in a DataSet object, how to make changes to that data, and how to write those changes back to a database.

8.5.2 Finding Tables

The DataSet objects Tables property holds a TablesCollection object that contains the DataTable objects in the DataSet. The following code loops through all the tables in the DataSet and displays their names: Iterate through the tables in the DataSet ds. Dim dt As DataTable For Each dt In ds.Tables Console.WriteLinedt.TableName Next This code does the same thing, using a numeric index on the TablesCollection object: 352 Iterate through the tables in the DataSet ds. Dim n As Integer For n = 0 To ds.Tables.Count - 1 Console.WriteLineds.Tablesn.TableName Next The TablesCollection object can also be indexed by table name. For example, if the DataSet ds contains a table named Categories, this code gets a reference to it: Dim dt As DataTable = ds.TablesCategories

8.5.3 Finding Rows