ADO.NET Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

Read data using ADO.NET with a DataSet and DataAdapter

Back to: ADO.NET Tutorial

To read data using ADO.NET with a DataSet and DataAdapter, you can follow these steps:


1. Create a Connection

Set up a connection to your database using a connection object, such as SqlConnection.

2. Initialize a DataAdapter

The DataAdapter executes a query or stored procedure and fetches the data into a DataSet.

3. Fill the DataSet

The Fill method of the DataAdapter populates the DataSet with data from the database.

4. Access the Data

You can access the data in the DataSet using its Tables and Rows properties.


Example Code to Read Data

using System;
using System.Data;
using System.Data.SqlClient;
class Program {
static void Main()
{
// Step 1: Define the connection string
string connectionString = "your_connection_string_here";
// Step 2: Define the query to fetch data
string query = "SELECT * FROM YourTable";
// Step 3: Create a DataSet
DataSet dataSet = new DataSet();
// Step 4: Establish a connection and initialize the DataAdapter
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connection);
// Step 5: Fill the DataSet with data
dataAdapter.Fill(dataSet, "YourTable"); }
// Step 6: Access the data in the DataSet
DataTable table = dataSet.Tables["YourTable"];
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
Console.Write($"{row[column]} \t");
}
Console.WriteLine();
}
}
}

Explanation of the Code

  1. Connection String:

    • Replace "your_connection_string_here" with your database's connection string.
  2. Query:

    • Replace "SELECT * FROM YourTable" with your desired SQL query to fetch data.
  3. DataSet:

    • A DataSet is created to hold the data retrieved from the database.
  4. DataAdapter:

    • The SqlDataAdapter is used to execute the query and populate the DataSet.
  5. Fill Method:

    • The Fill method fetches data from the database and loads it into the DataSet.
  6. Iterating Through Data:

    • Access the specific DataTable within the DataSet and iterate through its rows and columns to read the data.

Sample Output

For a table YourTable with columns ID, Name, and Age, the output might look like:


1 John 25
2
Alice 30
3
Mark 22


This approach allows you to efficiently retrieve and display data using ADO.NET in a disconnected manner.

Scroll to Top