c# - how to check if sqldatareader return any value -


here code came with::

reader = cmd.executereader(); reader.read(); if (reader.read())     intq = int.parse(reader[0].tostring()); else     intq = 0;  txtblck.text = intq.tostring(); reader.close(); 

but causes execute else, , if this:

reader = cmd.executereader(); if (reader.read())     intq = int.parse(reader[0].tostring()); else     intq = 0;  txtblck.text = intq.tostring(); reader.close(); 

the if return true, how should this?

reader.read() advances reader next record, reader set before first record. if calling reader.read() returns false means unable advance next record (i.e. current record last record).

this means if wish read first record need call reader.read() once, , if reader.read() returns false means there no records - so:

using (var reader = cmd.executereader()) {     if (reader.read())     {         intq = int.parse(reader[0].tostring());     }     else     {         intq = 0;     } } txtblck.text = intq.tostring(); 

fyi int.parse throw exception if first record null - different having 0 rows. perhaps should check null values, or use int.tryparse instead.


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -