6

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

2 Answers 2

10

try...

if(Dr1.HasRows)
{
   //....
}
Sign up to request clarification or add additional context in comments.

1 Comment

Please remember to check for NULL like Nikhil D did.
6
if (Dr1 == null || !Dr1.HasRows) {
    // Do something
}

4 Comments

Tx for answer. Can you plz explain me difference between checking Dr1 and Dr1.HasRows.
If Dr1==null is true, it will stop the evaluation - ||(OR) operator has no need to evaluate the right hand side of the expression if it knows the left hand side is true.
no..you didn't get it. I asked ,what does it mean by (DataReader = null) and what is mean by (dataReader.HasRows = false) ? What is the dif between them?
NULL just mean that you try to call Dr1 that is not initialized (null). And Hasrows means it is initialised but has no data(rows)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.