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

26,111

Solution 1

try...

if(Dr1.HasRows)
{
   //....
}

Solution 2

if (Dr1 == null || !Dr1.HasRows) {
    // Do something
}
Share:
26,111
devan
Author by

devan

Software Engineer at Virtusa Pvt Ltd.

Updated on June 02, 2020

Comments

  • devan
    devan almost 4 years

    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