using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(sqlCommand, connection))
{
command.CommandType = CommandType.Text;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
DataTable datatable = new DataTable();
datatable.Load(reader);
return datatable;
}
}
}
Running this code returns an empty DataTable. However, looping through reader.Read() and printing to the debug console shows that the reader has data and it prints the expected data. Also, When I expand the reader object during debugging, hasRows is true and the field count is right for the number of columns returned.
There was a similar post here
Trouble loading SQL Data Reader data into DataTable
but the answer essentially was, just don't use it, use a SqlDataAdapter. I would prefer to use it and the DataTable has a load method that takes an IDataReader DataTable.Load(IDataReader). I just don't know why the reader is working when I print it to the debug window but not when I load it into the DataTable. Am I just overlooking something?



SqlDataAdapterand using it'sFillmethod?SqlDataAdapterbut I am just curious why the appropriate method on the DataTable isn't working... SqlDataReader is much faster and I would prefer to use it. Here is some info on the differences stackoverflow.com/a/1676809/3866019DataTable.Loaduses a data adapter internally anyway :) All those "benefits" of usingSqlDataReaderthat are in the answer you linked only apply when you don't use the reader to fill aDataTable(which shouldn't be unexpected, since data adapter simply fills a data table using the data reader; if you do that manually using a data reader instead, where would you expect any benefit? You're doing the exact same thing. The cost is in the data table.). Be careful about accepting advice like this without understanding what actually happens - it's going to hurt.DataTable.Loadworks just fine for me. If you keep everything as is and use a data adapter to fill the table instead, does it actually work? Do you have multiple result sets? What does the command do?