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?
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With