Search code examples
c#datatableidatareader

Why can't DataTable.Load(IDataReader) load one row?


I am using DataTable.Load(IDataReader) to load data from db.
When I load one record, DataTable.Rows.Count shows a count of 0, but when I load more than record DataTable.Rows.Count shows the right Count.

Does this mean DataTable.Load Method takes two rows and above?
This article was helpful but didn't answer my question
https://msdn.microsoft.com/en-us/library/system.data.datatable.load(v=vs.110).aspx.

Code

DataTable dt= new Datable
IDataReader rsg = DataClass.GetDBResults("sp_GetNames", "@Names", names);
 if (rsg.Read())
        {   
           dt.Load(rsg);
           int num = dt.Rows.Count;
                //More Code
        }

num is 0 if the procedure,sp_GetNames returns one record.


Solution

  • You're calling Read(), which reads the first record, and then you're calling Load(). The problem is that, after calling Read(), the pointer to the "current record" in rsg has already moved past the first record and is pointing to the next record (if there is one). The call to Load() is only going to read the rest of the records, since IDataReader is a forward-only mechanism.

    Call Load() without the first call to Read().