未将对象引用设置为对象的实例 c# 错误

use*_*526 2 c# sql

我需要检查记录是否保存到数据库中。如果它保存在数据库中打开另一个表单,否则显示一条消息,它不在数据库中。
如果记录不在数据库中,我会收到此错误Object reference not set to an instance of an object.
这是我的代码,请帮助我在此处找到错误:

string cmdStr = "Select NO from COM_LIST_EXPORT where NO = '" + txtNO.Text + "'";
SqlCommand cmd = new SqlCommand(cmdStr, CN);
int count = (int)cmd.ExecuteScalar();
if (count == Convert.ToInt32(txtNO.Text))
{
    Archive_Sader dd = new Archive_Sader();
    dd.Show();
}

else
{
    MessageBox.Show("please save first");
}
Run Code Online (Sandbox Code Playgroud)

Sri*_*vel 6

ExecuteScalarnull找不到记录时返回。

所以当null -> int你试图施法时,你会得到一个NullReferenceException

试试这个。

int count = Convert.ToInt32(cmd.ExecuteScalar());
Run Code Online (Sandbox Code Playgroud)

Convert.ToInt320参数为 时将返回null