Convert a DataReader to DataTable in ASP.NET using C# or VB.net :

Jan 4, 2012 By Anil Gaikwad

While we are working with datareader when you want to bind data to a control which gets binded to a datatable only, that time you can convert that datareader to Datatable. So that you can bind that datatable to the Gridview which can be performed as follows.

To Convert a DataReader to DataTable you need to follow following steps:


  • Create a Sqlcommand object and pass query and connection to it.
Dim oCommand As SqlCommand Dim cmd As SqlCommand = New SqlCommand("SQL QUERY",oConnection)
  • Then you can execute that Procedure using Executereader and load that datareader into Datatable using Load method of the DataTable.This method is useful when you need to quickly create a DataTable, without using a DataAdapter.
Dim dr As SqlDataReader = cmd.ExecuteReader() Dim dt As DataTable = New DataTable() dt.Load(dr)
Note: If you want DataReader back from DataTable we useDataTable.CreateDataReader()

Complete Code


C#.net Example:

SqlConnection oConnection = new SqlConnection("Conection String"); SqlCommand cmd = new SqlCommand("SQL QUERY", oConnection); oConnection.Open(); SqlDataReader dr = cmd.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(dr); oConnection.Close();

VB.net Example:

Dim oConnection As oConnection = New SqlConnection("Conection String") Dim cmd As SqlCommand = New SqlCommand("SQL QUERY", oConnection) oConnection.Open() Dim dr As SqlDataReader = cmd.ExecuteReader() Dim dt As DataTable = New DataTable() dt.Load(dr) oConnection.Close()