我得到的对象引用未设置为对象的实例

我已经将代码更改为此代码但现在我得到另一个问题,即对象引用未设置为对象的实例。 错误是:

string Password = Pass.ExecuteScalar().ToString().Replace(" ", ""); protected void btn_login_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection( ConfigurationManager .ConnectionStrings["RegistrationCTIConnectionString"].ConnectionString); conn.Open(); string checkuser = "Select count(*) from [tblEmployee] where UserID= '" + txt_userID + "'"; SqlCommand com = new SqlCommand(checkuser, conn); int temp = Convert.ToInt32(com.ExecuteScalar().ToString()); conn.Close(); if (temp != 1) { conn.Open(); string checkPassword = "Select Password from [tblEmployee] where UserID= '" + txt_userID + "'"; SqlCommand Pass = new SqlCommand(checkPassword, conn); string Password = Pass.ExecuteScalar().ToString().Replace(" ", ""); if (Password == txt_password.Text) { Session["New"] = txt_userID.Text; Response.Write("Password is correct."); Response.Redirect("~/Homepage.aspx"); } } else { Response.Write("Login is incorrect."); } } 

你最好做这样的事……

 var Password = Pass.ExecuteScalar(); if (Password != null) Password.ToString().Replace(" ", ""); 

通过在可能为nullobject上调用.ToString().Replace()等,您将获得此exception。

这里的行if (temp != 1) ,需要是if (temp != 0) ,因为如果找不到用户,你将输入该代码块。 如果之前的结果为0 ,则IF语句中的下一个SQL查询将找不到用户。 因此, Password将为null ,因此错误。

另外,作为旁注,有助于防止SQL Injection

 string checkPassword = "Select Password from [tblEmployee] where UserID=@UserId"; SqlCommand Pass = new SqlCommand(checkPassword, conn); Pass.Parameters.Add(new SqlParameter("UserId", txt_userID));