Reputation: 141
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?
Upvotes: 1
Views: 951
Reputation: 122
you are inversing the steps :
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 :
}
Upvotes: 2