6.3 Using Typed DataSets
In most cases, you can use your Typed DataSet everywhere you would normally use a DataSet. Your Typed DataSet directly derives from DataSet so all the DataSet-related classes and methods will work. One of the distinct advantages of using a Typed DataSet is that elements of the DataSet are strongly typed and strongly named. The use of the new class is a little different than our old DataSet examples, as shown in Listing 6.4.
Listing 6.4: Using a Typed DataSet
... // Create the Customer DataAdapter SqlDataAdapter customerAdapter = new SqlDataAdapter("SELECT * FROM CUSTOMER", conn); // Create the Invoice DataAdapter SqlDataAdapter invoiceAdapter = new SqlDataAdapter("SELECT * FROM INVOICE", conn); // Create the DataSet CustomerTDS typedDS = new CustomerIDS(); // Use the DataAdapters to fill the DataSet customerAdapter.Fill(typedDS, "Customer"); invoiceAdapter.Fill(typedDS, "Invoice"); // Show the address and # of invoices for each customer foreach(CustomerTDS.CustomerRow custRow in typedDS.Customer) { Console.WriteLine(custRow.FullName); Console.WriteLine(custRow.Address); Console.WriteLine("{0}, {1} {2}", custRow.City, custRow.State, custRow.Zip); Console.WriteLine("{0} (hm)", custRow.IsHomePhoneNull() ?"" : custRow.HomePhone); Console.WriteLine("{0} (bus)", custRow.IsBusinessPhoneNull() ? "" : custRow.BusinessPhone); Console.WriteLine("Invoices: " + custRow.GetChildRows("CustomerInvoice").Length); Console.WriteLine(""); }
When filling the Typed DataSet with data, you can deal with the new class just like a DataSet (because it derives directly from it). Once we fill it, we can use the typed accessors to get at rows and columns in a more direct way than with an untyped DataSet.
Because we allowed our HomePhone and BusinessPhone columns to be null, we need to check to see whether they are null before accessing them. If you do not do this, you will get a TypedDataSetException thrown unless you have used annotations to modify the generated code.