In this article I will explain with an example, how to populate (fill) DataTable using DataReader in ASP.Net using C# and VB.Net.
The DataTable will be populated with records from the DataReader using Load method of the DataTable.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Converting DataReader to DataTable using C# and VB.Net
Inside the Page load event handler, the records from the Customers table are fetched using SqlDataReader.
Finally, a new DataTable is created and the DataReader records are loaded into the DataTable using its Load method.
C#
protected void Page_Load(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
using (DataTable dt = new DataTable())
{
dt.Load(sdr);
}
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim constring As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constring)
Using cmd As SqlCommand = New SqlCommand("SELECT * FROM Customers", con)
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
Using dt As DataTable = New DataTable()
dt.Load(sdr)
End sing
End Using
End Using
End Using
End Sub
Screenshot
Downloads