Free mag vol1 | Page 926

CHAPTER 22  ADO.NET PART II: THE DISCONNECTED LAYER Inserting DataTables into DataSets At this point, your DataTable object is complete. The final step is to insert the DataTable into the carsInventoryDS DataSet object using the Tables collection, like this: static void FillDataSet(DataSet ds) { ... // Finally, add our table to the DataSet. ds.Tables.Add(inventoryTable); } Now update your Main() method to call FillDataSet(), passing in your local DataSet object as an argument. Next, pass the same object into a new (yet to be written) helper method named PrintDataSet(), as follows: static void Main(string[] args) { Console.WriteLine("***** Fun with DataSets *****\n"); ... FillDataSet(carsInventoryDS); PrintDataSet(carsInventoryDS); Console.ReadLine(); } Obtaining Data in a DataSet The PrintDataSet() method simply iterates over the DataSet metadata (using the ExtendedProperties collection) and each DataTable in the DataSet, printing out the column names and row values using the type indexers. static void PrintDataSet(DataSet ds) { // Print out the DataSet name and any extended properties. Console.WriteLine("DataSet is named: {0}", ds.DataSetName); foreach (System.Collections.DictionaryEntry de in ds.ExtendedProperties) { Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value); } Console.WriteLine(); // Print out each table. foreach (DataTable dt in ds.Tables) { Console.WriteLine("=> {0} Table:", dt.TableName); // Print out the column names. for (int curCol = 0; curCol < dt.Columns.Count; curCol++) { Console.Write(dt.Columns[curCol].ColumnName + "\t"); } Console.WriteLine("\n----------------------------------"); 872 l