question about oleDbDataReader HasRows properties

C

Claudia Fong

Hi,

I'm using the oleDbDataReader HasRows properties to detect wheter my
table contains a record with the parameter below:


oleDbConnection1.Close();
objreturnst.Parameters["DEPT_CODE"].Value = comboBox2.Text;
objreturnst.Parameters["ST_CODE"].Value = comboBox1.Text;
oleDbConnection1.Open();
OleDbDataReader objreturn = objreturnst.ExecuteReader();
if(objreturn.HasRows) --> this should be false, but it seems it is
always true.. :(
{
objreturn.Read();
retqty = Convert.ToDouble(objreturn["Expr1"]);
}

The SQL statement is:
this.objreturnst.CommandText = "SELECT SUM(TRAN_QTY) AS Expr1 FROM
TRAN2005 WHERE (TRAN_TYPE = \'7\') AND (DEPT_CODE = ?) AND (ST_CODE =
?)";

Since the expression objreturn.HasRows isn't false, so it will generate
the error: Object cannot be cast from DBNull to other types.

I don't know if there's any mistakes in my code, but can someone help
me?

Cheers!

Claudi
 
N

Nathan Baulch

I don't know if there's any mistakes in my code, but can someone help

A better way to tell if any rows are available is to look at the return
value of objreturn.Read().
Also, you should probably cast the return value directly to the expected
type rather than using Convert.ToDouble which is a little less efficient.

using (OleDbDataReader objreturn = objreturnst.ExecuteReader())
{
if (objreturn.Read())
{
if (objreturn[0] is double)
retqty = (double) objreturn[0];
}
}


Nathan
 
Top