Replacing a DataReader with a DataTable
Asked Answered
C

2

47

I'm adapting some code that someone else wrote and need to return a DataTable for time's sake.

I have code like this:

using (SqlCommand command = new SqlCommand(query, conn))
{
      //add parameters and their values

      using (SqlDataReader dr = command.ExecuteReader())
      {
          return dr;
      }

But what's the best way to return a datatable?

Colver answered 14/12, 2012 at 0:17 Comment(0)
F
91

Use the DataTable.Load method to fill your table with values from the SqlDataReader:

using (SqlDataReader dr = command.ExecuteReader())
{
    var tb = new DataTable();
    tb.Load(dr);
    return tb;
}
Flawy answered 14/12, 2012 at 0:25 Comment(0)
F
12

By using a DBDataAdapter

excerpt from ms documentation

// Create the DbDataAdapter.
DbDataAdapter adapter = new DbDataAdapter();
adapter.SelectCommand = command;

// Fill the DataTable.
DataTable table = new DataTable();
adapter.Fill(table);
Fellers answered 14/12, 2012 at 0:25 Comment(1)
It says that I cannot create an instance of the abstract classRedingote

© 2022 - 2024 — McMap. All rights reserved.