-5

When my select command does not have any result, it throws an exception. Instead I want to continue with the process without exception. How to control this by checking whether there is data retrieved from the select statement?

Here is my query:

sqlid = new SqlCommand("SELECT TOP 1 Proj_id FROM Proj_details WHERE Front_end = '" + strfrontend + "'ORDER BY Date_time desc", con);
id = sqlid.ExecuteScalar().ToString();
PVitt
  • 10,654
  • 4
  • 46
  • 81
Arun
  • 7
  • 1
  • 1

5 Answers5

4

Using exceptions to control program flow (as suggested by other answers) is the wrong solution. If its acceptable to return no results, check the value returned from ExecuteScalar() before calling ToString() on it.

By definition, ExecuteScalar will return null if there are no results.

object val = sqlid.ExecuteScalar();
if( val != null ){
    id = val.ToString();
}else{
    // do something (or nothing) and continue
}

See also: ExecuteScalar throws NullReferenceException

Community
  • 1
  • 1
Tim Medora
  • 51,363
  • 11
  • 111
  • 149
  • hi tim, thanks for you explanation and the link to the other question, never thought to check the if the value was null... i guess that solves the problem as well. – wterbeek Aug 08 '12 at 06:56
  • Thanks Tim, the down vote was deserved as it was bad practice. – wterbeek Aug 08 '12 at 07:02
0

Try to use ExecuteReader instead of ExecuteScalar and handle empty result this way:

SqlCommand sqlid = new SqlCommand("SELECT TOP 1 Proj_id FROM Proj_details WHERE Front_end = '" + strfrontend + "'ORDER BY Date_time desc", con);

SqlDataReader dr = sqlid.ExecuteReader();
if (dr.Read())
{
 id  = dr[0].ToString();
}
else
{
    // handle empty result here
}
Dmitriy Konovalov
  • 1,707
  • 14
  • 13
0

Will this suffice?

 SqlDataReader rd = cmdLoad4.ExecuteReader();
 if (rd.HasRows)
{
// input what you want.
}
else
{
//input the exception
}
Noobster
  • 93
  • 10
-1

Would a try-catch block not work?

    try
    {
        //Execute your SQL-statement here        
    }
    catch(SqlException)
    {
        //If you want something specific to happen when the
        //exception is thrown, put that here.
    }

http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.80).aspx

  • -1 using exceptions to control program flow is poor practice, especially when the exception is so easy to prevent. – Tim Medora Aug 08 '12 at 06:49
-1

encapsulate it with a try/catch statement :

try
{
    sqlid = new SqlCommand("SELECT TOP 1 Proj_id FROM Proj_details 
                           WHERE Front_end = '" + strfrontend 
                           + "'ORDER BY Date_time desc", con
                           ); 
    id = sqlid.ExecuteScalar().ToString();
}
catch(exception)
{
   // do something with the exception
}
wterbeek
  • 431
  • 9
  • 26
  • 1
    -1 using exceptions to control program flow is poor practice, especially when the exception is so easy to prevent. – Tim Medora Aug 08 '12 at 06:48