我有这个代码可能返回没有找到结果 - 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();
Run Code Online (Sandbox Code Playgroud)
我得到这个例外:
NullReferenceException: Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)
愿有人帮我解决这个问题吗?
试试这个:
result = (sqlcom.ExecuteScalar() ?? "").ToString();
Run Code Online (Sandbox Code Playgroud)
如果返回null,则结果为空字符串.您可以通过if语句处理该情况并向用户通知一些消息,例如:
object r = sqlcom.ExecuteScalar();
if(r != null) result = r.ToString();
else {
//code to handle the null case here...
}
Run Code Online (Sandbox Code Playgroud)