4

I have got this code that might return no results found - null

 String result
 string searchUby = "SELECT text FROM rooms WHERE year=@year AND event=@eventAND text=@text AND z is NULL";
                SqlCommand sqlcom = new SqlCommand(searchUby, conn);
                sqlcom.Parameters.AddWithValue("@event",event.Text);
                sqlcom.Parameters.AddWithValue("@text", cb_room.SelectedItem);
                sqlcom.Parameters.AddWithValue("@year",klientClass.Year());
                conn.Open();                  
                result = sqlcom.ExecuteScalar().ToString(); // on this line ex occurs

                conn.Close();

I get this exception:

NullReferenceException: Object reference not set to an instance of an object. 

May someone help me with solving this?

Marek
  • 3,555
  • 17
  • 74
  • 123

3 Answers3

6

Try this:

result = (sqlcom.ExecuteScalar() ?? "").ToString();

If it returns null, the result will be an empty string. You can handle that case by an if-statement and notify some message to the user, such as like this:

object r = sqlcom.ExecuteScalar();  
if(r != null) result = r.ToString();
else {
  //code to handle the null case here...
}
King King
  • 61,710
  • 16
  • 105
  • 130
2

Your ExecuteScalar() is returning a DBNull. You'll have this issue everywhere you use ExecuteScalar, so you should think of using a Generic Helper Function like below that SO User Rein's has written up in a related Question here.

Just do this:

result = ConvertFromDBVal<string>(sqlcom.ExecuteScalar());

using the generic function:

public static T ConvertFromDBVal<T>(object obj)
{
    if (obj == null || obj == DBNull.Value) {
        return default(T); // returns the default value for the type
    }
    else
    {
        return (T)obj;
    }
}
Community
  • 1
  • 1
Shiva
  • 20,575
  • 14
  • 82
  • 112
1
result = sqlcom.ExecuteScalar() !=null ?  sqlcom.ExecuteScalar().ToString() : string.Empty;
senthilkumar2185
  • 2,536
  • 3
  • 22
  • 36