With the code below:
SqlCeDataReader myReader = cmd.ExecuteReader(CommandBehavior.SingleRow);
itemID = myReader.GetString(0);
packSize = myReader.GetString(1);
...I get an exception, "No data exists for the row/column"
I want it to silently "abort" rather than throwing an exception in this case. Is there a way to test first before the attempted assignment?
I tried this, but it does no good:
SqlCeDataReader myReader = cmd.ExecuteReader(CommandBehavior.SingleRow);
if (null != myReader.GetString(0))
{
itemID = myReader.GetString(0);
}
if (null != myReader.GetString(1))
{
packSize = myReader.GetString(1);
}
Another possibility would be to wrap it in a try..catch and "eat" the exception, but I don't know if that's the best way to go...
This is because you didn't call Read()
method after obtaining the DataReader
. This does not mean that the result contains no data. It means that the row contains no data.
using (SqlCeDataReader myReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (myReader.Read()) // It returns `false` if there is no data
{
itemID = myReader.GetString(0);
packSize = myReader.GetString(1);
}
}
If the result can contain multiple rows and you want to check to see if the result contains any data, use HasRows
:
using (SqlCeDataReader myReader = cmd.ExecuteReader())
{
if (myReader.HasRows)
{
while (myReader.Read())
{
// read values from `myReader`
}
}
}