Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handing ExecuteScalar returning null when no results are found

Tags:

c#

sql

sql-server

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?

like image 743
Marek Avatar asked Jan 12 '23 19:01

Marek


1 Answers

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...
}
like image 70
King King Avatar answered Jan 27 '23 20:01

King King