ADO.NET provides the ability to retrieve data from any number of data sources and to work with that data in memory. The DataSet object represents a local cache of data that is disconnected from the original source. The DataSet object can provide a relational view of data: It can contain tables, columns, rows, constraints, and relationships. The DataTable object represents one table of in-memory data. It supports rows and columns with schema information, much like an array, but it’s far more powerful. You can retrieve a DataTable by retrieving data from a data source, or you can create and fill the DataTable manually. The DataTable class exposes collections of rows and columns, where a row represents a reference to an actual row of data, and a column contains information about the schema for one of the columns of data. A DataTable’s Rows property contains a collection of DataRow objects, and its Columns property contains a collection of DataColumn objects. You can access and manipulate data in a DataTable’s rows by using a DataRow object. When you work with the Rows property of the DataTable, you can:
- Access a DataRow object within the Rows collection by index, enumerator, or lookup.
- Iterate through all rows, using a DataRow object as the iterator.
- Iterate through all the rows, using an integer as the indexer.
- Use the NewRow method of the Rows collection to add a new row, which returns a new DataRow object.
DataSets can be untyped or typed. When you directly instantiate the DataSet class, as shown in the following code, you will have an untyped DataSet.
var nwindDataSet = new DataSet();
A typed DataSet inherits from the DataSet class. It contains strongly typed properties for each DataTable. This means you can refer to tables and columns by names. If you are using an untyped DataSet, you can refer to the Products table by using myDataSet.Tables(“Products”). You can refer to the ProductID column in the Products table by using myDataSet.Tables(“Products”).Columns(“ProductID”). If you are working with a typed DataSet, you can use myDataSet.Products to refer to the table and myDataSet.Products.ProductID to refer to the column. When you create a data source via the Data Source Configuration Wizard, Visual Studio creates a typed DataSet that includes the tables you specify.
Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.