How To Convert A SqlDataReader To A DataTable Using C#



TODO:

Have you ever wanted to convert a SqlDataReader to a DataTable in C#?

 

SOLUTION:

 

DataTable datatable = null;
string ErrorMessage = "";

try
{
     using (SqlConnection myConnection = new SqlConnection(ConnectionString))
     {
           using (SqlCommand cmd = new SqlCommand("some sql here", myConnection))
           {
                 myConnection.Open();
                 using (SqlDataReader reader = cmd.ExecuteReader())
                 {
                       datatable = new DataTable();
                       datatable.Load(reader);
                 }
           }
      }
}
catch (Exception ex)
{
     ErrorMessage = ex.Message;
}

 

NOTES:

There are no notes on this topic.



Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading