Home > Code > C# > How to load DataTable using DataReader in ADO.NET?

How to load DataTable using DataReader in ADO.NET?

by Spidy   on May 18, 2011   Category: C#   |  Views: 1547    |  Points: 25   |  Silver 


Usually we read the data ony by one from datareader but here in ADO.NET 2.0 introduces the new feature to load the datatable using Load() method with datareader. See the below code

Include the below namespace

using System;
using System.Data;
using System.Data.SqlClient;

Method to load datatable
private void LoadDataTable()
{
try
{
DataTable dtEmp = new DataTable();
using (SqlConnection conn = new SqlConnection("ConnectionString....")) //Provide Connection string
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM Employees";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
dtEmp.Load(dr);
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}




Post Code  |  Code Snippet Home

User Responses


No response found, be the first to review this code snippet.

Submit feedback about this code snippet

Please sign in to post feedback

Latest Posts