需要处理空引用异常

时间:2015-04-15 08:50:37

标签: c# sql asp.net

enter image description here我需要以某种方式处理代码txtHandle.Text = command.ExecuteScalar().ToString();的这一部分中的空异常 我的整个代码是:

 SqlConnection con = new SqlConnection(constr);
        string fNameTemp = txtUsername.Text;
        string sqlquery = ("SELECT Username FROM Userstbl 
                             WHERE (Username =  '" + fNameTemp + "')");
        con.Open();
        SqlCommand command = new SqlCommand(sqlquery, con);
        txtHandle.Text = command.ExecuteScalar().ToString();
        con.Close();

2 个答案:

答案 0 :(得分:5)

在这种情况下,ExecuteScalar肯定会返回string(或null),因此无需调用ToString(),只需投出它:

txtHandle.Text = command.ExecuteScalar() as string;

或者,如果您需要在null案例中将文字设置为null以外的其他操作:

var result = command.ExecuteScalar() as string;

if (result != null)
{
    txtHandle.Text = result;
}
else
{
    ...
}

答案 1 :(得分:1)

您可以使用字符串,而不是将查询结果分配给TextBox。字符串是引用类型,因此可以为null。

你可以这样:

string result = command.Executescalar() as string;
if (result != null) {
     txtHandle.Text = result 
}

或者您可以使用String.IsNullorEmpty方法

相关问题