There are plenty alternatives and methods for filling a DataSet / Datatable. This one in particular is simple, easy and to the point. In often cases I usually hydrate custom objects for performance reasons, however for those times you need something done quick or perhaps dynamically, try filling a datable as follows: DataTable.Load(SqlDataReader)

  1. DataTable table = new DataTable();
  2. SqlConnection conn = new SqlConnection("the connection string");
  3. SqlCommand command = new SqlCommand("proc or query", conn);
  4. command.CommandType = System.Data.CommandType.StoredProcedure;
  5. command.Connection.Open();
  6. using(SqlDataReader reader = command.ExecuteReader())
  7. {
  8.         table.Load(reader);
  9. }

Its syntactically easy, and using the DataReader objects makes its performance quite well to boot.

A quick note on this method that is not well known: calling DataTable.Load(SqlDataReader) will automatically advance the SqlDataReader to the next Result Set. For reading multiple result sets see:

One Comments