.NET Programming With Me

C# : Filling a DataTable from a SqlDataReader

The following code snippet shows you how to fill a DataTable from an SqlDataReader with only a few lines of code.


private DataTable GetDataTable()
{
  string sql = "SELECT * FROM MyTable";
  using (SqlConnection myConnection = new SqlConnection(connectionString))
  {
    using (SqlCommand myCommand = new SqlCommand(sql, myConnection))
    {
      myConnection.Open();
      using (SqlDataReader myReader = myCommand.ExecuteReader())
      {
        DataTable myTable = new DataTable();
        myTable.Load(myReader);
        myConnection.Close();
        return myTable;
      }
    }
  }
}

This code executes a DataReader (a SqlDataReader in this case, but you can also use other types, like an OleDbDataReader). It then passes this open reader into the Load method of the DataTable that takes care of copying the data from the reader into the DataTable.

Referenced from : here

No comments: