Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTable not loading SqlDataReader

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?

like image 812
asmithdev Avatar asked Dec 18 '22 21:12

asmithdev


1 Answers

It turns out I was just overlooking something and this is actually not an issue at all. The original code actually works fine. The preview of the DataTable object when debugging shows {} and looked empty to me. enter image description here

Then there was a property on the object called ExtendedProperties that had Count = 0, which obviously isn't a row count but I just glossed over and got Count = 0 stuck in my head.

enter image description here

If you find yourself in the same situation, scroll down when hovering the object and expand the Rows and you should see your row count in there. enter image description here

I got duped on this one... sorry for the stupidity on my part and thanks for the help everyone.

like image 163
asmithdev Avatar answered Jan 09 '23 02:01

asmithdev