Search code examples
c#datareader

Datareader.HasRow is wrong


Can anyone confirm or dispute a problem I'm having accessing an ACCDB database with a DataReader. I setup the DataReader and query the database. When I check DataReader.HasRows, I get true, no matter if records are present or not.

I've double verified that the data table is empty, no records at all, but DataReader.HasRows still says it got records.

If I go on and try DataReader.Read, when I know there are no records returned, I get an error saying "No data exists for the row/column." which would be expected.

Has anyone seen this before? Or can you say this doesn't happen?

Thanks

sql = @"SELECT a.License, a.ClassID, a.CurrentlyIn, a.TotalScans " +
    @"FROM Attendance a " +
    @"WHERE a.License = " + myScan.LicenseInt +
        @" AND a.ClassID = " + myScan.ClassID + ";";
_parent.StatusOutput(sql);

cmdDB = new OleDbCommand(sql, cnDB);
try
{
    //cnDB.Open();

    drDB = cmdDB.ExecuteReader();
    if (drDB.HasRows)
    {
        _parent.StatusOutput("Data reader has no rows");
    }
    else
    {
        _parent.StatusOutput("Data reader has rows.");
        drDB.Read();
        _parent.StatusOutput(drDB["License"].ToString() + ", " + drDB["ClassID"].ToString());
    }

There we go. Sorry for my confusion on how to post this.


Solution

  • In your sample code as it is here If reader HAS the rows then it prints the error

    and if reader Does not have the rows it prints that it Has and reads and throws exception

    swap:

    if (drDB.HasRows)
            {
                _parent.StatusOutput("Data reader has rows.");
                drDB.Read();
                _parent.StatusOutput(drDB["License"].ToString() + ", " + drDB["ClassID"].ToString());
    
                       }
            else
            {
                _parent.StatusOutput("Data reader has no rows");
    
            }