.NET Documentation

Datasets

A Dataset object represents a collection of DataTable objects. Together, these objects mimic the structure of a database, providing a disconnected, in-memory representation of data. Datasets are central to ADO.NET's data access capabilities, enabling efficient handling of data manipulation and synchronization between client and server.

Key Features of Datasets

Working with Datasets

The process of using a Dataset typically involves the following steps:

  1. Creating a Dataset: Instantiate a new Dataset object.
  2. Populating the Dataset: Use a DataAdapter (e.g., SqlDataAdapter, OleDbDataAdapter) to fill the Dataset with data from a data source. This is usually done by executing a command and mapping the results to a DataTable within the Dataset.
  3. Accessing Data: Navigate through the DataTable objects in the Dataset to access rows and columns.
  4. Manipulating Data: Modify, add, or delete rows within the DataTable objects.
  5. Updating the Data Source: Use the DataAdapter to send any changes made in the Dataset back to the original data source.

Example: Creating and Populating a Dataset

using System.Data; using System.Data.SqlClient; // Assume connectionString and sqlQuery are defined // Create a SqlConnection using (SqlConnection connection = new SqlConnection(connectionString)) { // Create a SqlDataAdapter using (SqlDataAdapter adapter = new SqlDataAdapter(sqlQuery, connection)) { // Create a Dataset object DataSet dataSet = new DataSet(); // Fill the Dataset with data // The data will be placed into a DataTable with a default name like "Table1" adapter.Fill(dataSet); // You can specify a table name if you prefer // adapter.Fill(dataSet, "Customers"); // Now you can access the data if (dataSet.Tables.Count > 0) { DataTable customersTable = dataSet.Tables[0]; // Or dataSet.Tables["Customers"] foreach (DataRow row in customersTable.Rows) { Console.WriteLine($"Customer Name: {row["CustomerName"]}"); } } } }
Note: While DataSet is powerful for disconnected scenarios and complex data manipulation, for simpler, forward-only data reading scenarios, consider using DataReader for better performance.

Related Topics