Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a datareader has rows or not in Asp.net

My code:

string sqlQuery1 = "select * from employees where depid=6";
SqlDataReader Dr1 = dbconn.RunQueryReturnDataReader(sqlQuery1);

if(Dr1.read()) {    //or if (Dr1["empname"] != DBNull.Value)

            while (Dr1.Read())
            {        
                Label1.Text = Dr1["empname"].ToString();  
                Label2.Text = Dr1["empdes"].ToString(); 
                ...

            }
            Dr1.Close();
 }
 else {
            Label1.text = "defaultValue";
            Label2.text = "defaultValue";
            ...
 }

I just want to check SqlDataReader has no records to display. If no records ,the labels should showdefault values preassigned by me or If has record display datareader value on label. (Assume either SqlDataReader has 1 recode or has norecord only)

How can I check first datareader hasRow or not?

I have tried two ways as above code.

  1. if(Dr1.read()) - this way working fine. But after execute If statement ,it has no value to display on labels , since read() will increase the pointer. As a result label1 ,Label2.. Nothing display.

  2. if (Dr1["empname"] != DBNull.Value)

    This way generate an exception when Sqldatareader has norows.

error: System.InvalidOperationException: Invalid attempt to read when no data is present

Please help me. tx

like image 711
devan Avatar asked Dec 08 '22 23:12

devan


2 Answers

try...

if(Dr1.HasRows)
{
   //....
}
like image 191
Ray Cheng Avatar answered Dec 26 '22 17:12

Ray Cheng


if (Dr1 == null || !Dr1.HasRows) {
    // Do something
}
like image 28
Nikhil D Avatar answered Dec 26 '22 16:12

Nikhil D