Home Asp.net How to Convert SqlDataReader to DataTable in Asp.net?

How to Convert SqlDataReader to DataTable in Asp.net?

2
0

Now here in this tutorial, I’ll explain how you can convert SqlDataReader to DataTable using Load() method with example code in asp.net c# as well as vb.net. Make sure you check out other tutorials as well if you liked this one!

In my previous tutorials, I’d explained how to bind gridview using executereader, difference between executereader executenonquery and executescalar, how to export gridview data to word excel text pdf, gridview inline insert update delete and other more cracking tutorials on Gridivew, Asp.net here.

To convert SqlDataReader to DataTable, we need to use Load() method of DataTable. Following is the syntax of DataTable Load() method:

DataTable Load() Syntax – [C#]

Following is the simple syntax of Load method in C#:

DataTable objDataTable = new DataTable();
objDataTable.Load(objDataReader);

Convert SqlDataReader to DataTable C#

Following is the sample example code that will convert sqldatareader to datatable:

//bind subject details to gridview
private void BindGridviewFileData()
{
try
{
string con = @”Data Source=datasource;Integrated Security=true;Initial Catalog=yourDB”;
using (SqlConnection sqlConn = new SqlConnection(con))
{
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.CommandText = “SELECT * FROM SubjectDetails”;
sqlCmd.Connection = sqlConn;
sqlConn.Open();
SqlDataReader objDataReader = sqlCmd.ExecuteReader();
DataTable objDataTable = new DataTable();
objDataTable.Load(objDataReader);
gvSubjectDetails.DataSource = objDataTable;
gvSubjectDetails.DataBind();
sqlConn.Close();
}
}
}
catch { }
}

DataTable Load() Syntax – [Vb.net]

Following is the simple syntax of Load method in C#:

Dim objDataTable As New DataTable()
objDataTable.Load(objDataReader)

Convert SqlDataReader to DataTable In Vb.net

Following is the sample example code:

‘bind subject details to gridview
Private Sub BindGridviewFileData()
Try
Dim con As String = “Data Source=datasource;Integrated Security=true;Initial Catalog=yourDB”
Using sqlConn As New SqlConnection(con)
Using sqlCmd As New SqlCommand()
sqlCmd.CommandText = “SELECT * FROM SubjectDetails”
sqlCmd.Connection = sqlConn
sqlConn.Open()
Dim objDataReader As SqlDataReader = sqlCmd.ExecuteReader()
Dim objDataTable As New DataTable()
objDataTable.Load(objDataReader)
gvSubjectDetails.DataSource = objDataTable
gvSubjectDetails.DataBind()
sqlConn.Close()
End Using
End Using
Catch
End Try
End Sub

LEAVE A REPLY

Please enter your comment!
Please enter your name here
Captcha verification failed!
CAPTCHA user score failed. Please contact us!