---
title: "ADO.NET DataSet Class"  
description: "The DataSet class in ADO.NET is a disconnected, in-memory representation of data. It can store multiple DataTable objects, along with relationships, c"  
author: "ICSM Computer"  
published: 2025-02-12  
updated: 2025-02-12  
canonical: https://www.mindstick.com/blog/305250/ado-dot-net-dataset-class  
category: "ado.net"  
tags: ["c#", "ado.net"]  
reading_time: 4 minutes  

---

# ADO.NET DataSet Class

The `DataSet` class in ADO.NET is a **[disconnected](https://www.mindstick.com/blog/300962/how-modern-life-disconnected-from-nature), in-memory representation** of data. It can store multiple `DataTable` objects, along with [relationships](https://www.mindstick.com/blog/11850/how-to-build-stronger-relationships-with-your-employees), constraints, and schema information. Unlike `DataReader`, `DataSet` works **without requiring an active [database connection](https://www.mindstick.com/forum/159617/how-to-connect-to-a-database-connection-in-java)** after retrieving the data.

## Namespace:

```cs
using System.Data;
```

#### Key Features of `DataSet`

1. **Stores [multiple tables](https://www.mindstick.com/forum/159848/how-to-get-multiple-tables-using-entity-framework-core)** in memory (`DataTable` objects).
2. **Works in a disconnected manner**, allowing data manipulation without an active connection.
3. **Maintains relationships** between tables using `DataRelation`.
4. **Supports constraints** such as primary [keys and foreign](https://answers.mindstick.com/qa/30985/what-are-primary-keys-and-foreign-keys) keys.
5. **Enables data operations** like filtering, sorting, and searching.

![ADO.NET DataSet Class](https://www.mindstick.com/blogs/4bb4c641-8072-4e89-860b-5d1f8905bb78/images/440a1e56-d929-4688-8dfe-5845b67a0543.jpg)

#### Creating a `DataSet` and Adding Tables

```cs
using System;
using System.Data;

class Program
{
    static void Main()
    {
        // Create a DataSet
        DataSet ds = new DataSet("CompanyDataSet");

        // Create a DataTable
        DataTable dt = new DataTable("Employees");

        // Define columns
        dt.Columns.Add("ID", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Age", typeof(int));

        // Add rows
        dt.Rows.Add(1, "Alice", 25);
        dt.Rows.Add(2, "Bob", 30);
        dt.Rows.Add(3, "Charlie", 22);

        // Add DataTable to DataSet
        ds.Tables.Add(dt);

        // Display data from DataSet
        foreach (DataRow row in ds.Tables["Employees"].Rows)
        {
            Console.WriteLine($"ID: {row["ID"]}, Name: {row["Name"]}, Age: {row["Age"]}");
        }
    }
}
```

#### Loading Data from a Database (`SqlDataAdapter`)

We can populate a `DataSet` from a database using `SqlDataAdapter`.

```cs
using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "Server=your_server;Database=your_db;Integrated Security=True;";
        DataSet ds = new DataSet();
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();

            // Define SQL query
            string query = "SELECT ID, Name, Age FROM Employees";

            // Fill DataSet
            SqlDataAdapter adapter = new SqlDataAdapter(query, conn);
            adapter.Fill(ds, "Employees"); // Fills DataSet with "Employees" table
            conn.Close(); // Close connection (Disconnected Mode)
        }
        // Display retrieved data
        foreach (DataRow row in ds.Tables["Employees"].Rows)
        {
            Console.WriteLine($"ID: {row["ID"]}, Name: {row["Name"]}, Age: {row["Age"]}");
        }
    }
}
```

**Proof of Disconnection**: After fetching the data, the connection is closed, but we can still work with the `DataSet`.

#### Searching and Filtering Data

**Searching (**`Select` **Method)**

```cs
DataRow[] result = ds.Tables["Employees"].Select("Age > 25");
foreach (DataRow row in result)
{
    Console.WriteLine($"Filtered Employee: {row["Name"]} ({row["Age"]})");
}
```

## Sorting Data

Although `DataSet` does not support direct sorting, we can use `DataView`:

```cs
DataView dv = new DataView(ds.Tables["Employees"]);
dv.Sort = "Age DESC";

foreach (DataRowView row in dv)
{
    Console.WriteLine($"{row["Name"]} - {row["Age"]}");
}
```

**Updating the Database from a** `DataSet`

Since `DataSet` is disconnected, changes must be **updated back** to the database using `SqlDataAdapter`.

```cs
using System.Data.SqlClient;

// Modify data
ds.Tables["Employees"].Rows[0]["Age"] = 35;  // Update age for first row

// Reconnect and update the database
using (SqlConnection conn = new SqlConnection(connectionString))
{
    SqlDataAdapter adapter = new SqlDataAdapter("SELECT ID, Name, Age FROM Employees", conn);
    SqlCommandBuilder builder = new SqlCommandBuilder(adapter); // Auto-generate SQL commands

    adapter.Update(ds, "Employees"); // Apply changes to DB
    Console.WriteLine("Database Updated!");
}
```

## Adding Relationships Between Tables

A `DataSet` can store **multiple related tables**. We can define **parent-child relationships** using `DataRelation`.

```cs
DataTable employees = new DataTable("Employees");
employees.Columns.Add("ID", typeof(int));
employees.Columns.Add("Name", typeof(string));

DataTable departments = new DataTable("Departments");
departments.Columns.Add("DeptID", typeof(int));
departments.Columns.Add("DeptName", typeof(string));
departments.Columns.Add("EmpID", typeof(int)); // Foreign Key

// Add tables to DataSet
ds.Tables.Add(employees);
ds.Tables.Add(departments);

// Define relation (1 Employee → Many Departments)
DataRelation relation = new DataRelation(
    "EmployeeDepartment",
    ds.Tables["Employees"].Columns["ID"],  // Parent
    ds.Tables["Departments"].Columns["EmpID"]  // Child
);

ds.Relations.Add(relation);
Console.WriteLine("Relationship Added Successfully!");
```

#### Converting `DataSet` to `XML`

The `DataSet` supports exporting data to XML format.

```cs
ds.WriteXml("CompanyData.xml");  // Save to XML file
Console.WriteLine("DataSet saved as XML!");
```

To load from XML:

```cs
ds.ReadXml("CompanyData.xml");
```

#### When to Use `DataSet`?

- **Multiple Tables**: When working with multiple tables and relationships.
- **Disconnected Mode**: When you don’t need a live database connection.
- **[Batch Processing](https://www.mindstick.com/forum/158518/what-is-the-difference-between-batch-processing-and-real-time-processing-in-big-data-applications)**: When you need to update [multiple rows](https://www.mindstick.com/forum/159373/how-to-bulk-update-multiple-rows-in-sql-server-at-a-time-with-different-matching-conditions) at once before saving to the database.
- **XML Support**: When you need to save/load data in XML format.

#### Summary

| Feature | `DataSet` (Disconnected) | `DataReader` (Connected) |
| --- | --- | --- |
| Stores Multiple Tables? | Yes | No |
| Works Without DB Connection? | Yes | No |
| Supports Filtering & Sorting? | Yes (via `DataView`) | No |
| Best for [Large Data](https://www.mindstick.com/interview/872/how-do-you-load-large-data-to-the-sqlserver-database)? | Yes (Batch Operations) | No (Real-time Only) |
| Supports XML? | Yes (`WriteXml()`) | No |

---

Original Source: https://www.mindstick.com/blog/305250/ado-dot-net-dataset-class

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
