Search code examples
c#databasems-accessoledbdatareader

How to check if OleDbDataReader is empty?


This is the code i am using to select Maximum RollNo based on Class field value. But when there is no data about Class Field in Table. Then Error is generated.

using (var conn = new OleDbConnection(DatabaseObjects.ConnectionString))
            {
                conn.Open();
                command = new OleDbCommand("select max(RollNo) as Roll from Students where Class = '"+cmbClass.Text+"'", conn);
                OleDbDataReader dr = command.ExecuteReader();
                if (!dr.IsDBNull(0))
                {
                    while (dr.Read())
                    {
                        i = Convert.ToInt32(dr["Roll"]);
                    }
                }

InvalidOperation Exception is occurring. I want to get value of RollNo if data is available in Table. If data is not available in Table then what should I do?


Solution

  • you are inversing the steps :

    • open the connection;
    • check is there is comming data;
    • check if the value is not null;
    • read the data;

    try this :

    while (dr.Read())
       {
           if (!dr.IsDBNull(0))
              {
                i = Convert.ToInt32(dr["Roll"]);
              }
       }
    

    while your are attending just single value, use executeScalar to get the value ;

      conn.Open();          
      command = new OleDbCommand("select isnull(max(RollNo),-1) as Roll from Students where Class = '"+cmbClass.Text+"'", conn);
      int rollNo = (int) command.ExecuteScallar();
      if(rollno !=-1)
      {
         // TODO :
      }