A Comprehensive Guide to DataTables, DataSets, and DataAdapters in C#.NET
Mastering DataTables, DataSets, and DataAdapters in C#.NET

A Comprehensive Guide to DataTables, DataSets, and DataAdapters in C#.NET

In C#.NET, managing and manipulating data is a crucial aspect of application development. DataTables, DataSets, and DataAdapters are essential components that facilitate data handling, particularly when dealing with databases. This guide aims to provide a thorough understanding of these components, how to use them, and the differences between them, complete with examples.

What is a DataTable?

A DataTable is an in-memory representation of a single table of data. It is part of the System.Data namespace and can store rows and columns of data. DataTables are useful for manipulating data locally within an application.

How to Use DataTables

Creating and Populating a DataTable:

using System;

using System.Data;

class Program

{

    static void Main()

    {

        // Create a new DataTable

        DataTable table = new DataTable("Products");

        // Add columns to the DataTable

        table.Columns.Add("ProductID", typeof(int));

        table.Columns.Add("ProductName", typeof(string));

        table.Columns.Add("Price", typeof(decimal));

        // Add rows to the DataTable

        table.Rows.Add(1, "Apple", 0.50m);

        table.Rows.Add(2, "Banana", 0.30m);

        table.Rows.Add(3, "Cherry", 0.75m);

        // Display the data

        foreach (DataRow row in table.Rows)

        {

            Console.WriteLine($"ID: {row["ProductID"]}, Name: {row["ProductName"]}, Price: {row["Price"]}");

        }

    }

}        

What is a DataSet?

A DataSet is an in-memory representation of a database-like structure. It can contain multiple DataTables and the relationships between them. DataSets are ideal for working with disconnected data where you need to manipulate data locally before committing changes to the database.

#### How to Use DataSets

Creating and Populating a DataSet:

using System;

using System.Data;

class Program

{

    static void Main()

    {

        // Create a new DataSet

        DataSet dataSet = new DataSet("Store");

        // Create DataTables

        DataTable productsTable = new DataTable("Products");

        productsTable.Columns.Add("ProductID", typeof(int));

        productsTable.Columns.Add("ProductName", typeof(string));

        productsTable.Columns.Add("Price", typeof(decimal));

        DataTable ordersTable = new DataTable("Orders");

        ordersTable.Columns.Add("OrderID", typeof(int));

        ordersTable.Columns.Add("ProductID", typeof(int));

        ordersTable.Columns.Add("Quantity", typeof(int));

        // Add rows to the DataTables

        productsTable.Rows.Add(1, "Apple", 0.50m);

        productsTable.Rows.Add(2, "Banana", 0.30m);

        productsTable.Rows.Add(3, "Cherry", 0.75m);

        ordersTable.Rows.Add(1001, 1, 5);

        ordersTable.Rows.Add(1002, 2, 3);

        // Add DataTables to the DataSet

        dataSet.Tables.Add(productsTable);

        dataSet.Tables.Add(ordersTable);

        // Display the data

        foreach (DataTable table in dataSet.Tables)

        {

            Console.WriteLine($"Table: {table.TableName}");

            foreach (DataRow row in table.Rows)

            {

                foreach (DataColumn column in table.Columns)

                {

                    Console.Write($"{column.ColumnName}: {row[column]} ");

                }

                Console.WriteLine();

            }

            Console.WriteLine();

        }

    }

}        

What is a DataAdapter?

A DataAdapter acts as a bridge between a DataSet/DataTable and a data source for retrieving and saving data. It uses commands to execute SQL statements to retrieve data and update the database.

#### How to Use DataAdapters

Using a DataAdapter to Fill a DataSet:

using System;

using System.Data;

using System.Data.SqlClient;

class Program

{

    static void Main()

    {

        string connectionString = "your_connection_string_here";

        string query = "SELECT ProductID, ProductName, Price FROM Products";

        using (SqlConnection connection = new SqlConnection(connectionString))

        {

            SqlDataAdapter adapter = new SqlDataAdapter(query, connection);

            // Create a DataSet

            DataSet dataSet = new DataSet();

            // Fill the DataSet with data from the database

            adapter.Fill(dataSet, "Products");

            // Display the data

            DataTable productsTable = dataSet.Tables["Products"];

            foreach (DataRow row in productsTable.Rows)

            {

                Console.WriteLine($"ID: {row["ProductID"]}, Name: {row["ProductName"]}, Price: {row["Price"]}");

            }

        }

    }

}        

Differences Between DataTable, DataSet, and DataAdapter

1. DataTable:

- Represents a single table of in-memory data.

- Suitable for simple data manipulations and binding to UI controls.

- Can be used independently or as part of a DataSet.

2. DataSet:

- Represents a collection of DataTables and the relationships between them.

- Ideal for handling complex data operations and working with multiple tables.

- Supports disconnected data operations, allowing you to manipulate data locally.

3. DataAdapter:

- Serves as a bridge between a DataSet/DataTable and a data source.

- Used for retrieving data from a database and saving changes back to the database.

- Provides methods to fill DataSets/DataTables and update the database with changes made in-memory.

Daily Life Example

Consider an online store scenario. The store's backend system needs to retrieve product data from a database, display it to users, allow users to add items to their cart, and finally process their orders.

- DataTable can be used to hold and display the list of products.

- DataSet can be used to manage both products and orders, maintaining the relationships between them.

- DataAdapter can be used to fetch the product data from the database and update the order details back into the database once the user completes a purchase.

#DotNet #CSharp #DataHandling #DataTables #DataSets #DataAdapters #Programming #SoftwareDevelopment #DotNetGuru #TechSkills #LearnToCode

---

要查看或添加评论,请登录

Asharib Kamal的更多文章

社区洞察

其他会员也浏览了