简体   繁体   中英

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?

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 :
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM