當我運行代碼,並且我輸入了錯誤的用戶ID時,它不顯示錯誤消息「登錄錯誤。」。而是我就行收到一個錯誤:獲取「未將對象引用設置爲對象的實例」。錯誤
string Password = Pass.ExecuteScalar().ToString();
因此我得到這個錯誤「對象引用不設置到對象的實例。」如果沒有找到
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= @ID";
SqlCommand Pass = new SqlCommand(checkPassword, conn);
Pass.Parameters.Add(new SqlParameter("ID", txt_userID.Text));
string Password = Pass.ExecuteScalar().ToString();
if (!String.IsNullOrEmpty(Password) || Password.Trim().Length == 0)
if (Password == txt_password.Text)
{
Session["New"] = txt_userID.Text;
Response.Write("Password is correct.");
Response.Redirect("~/Homepage.aspx");
}
else
{
Response.Write("Incorrect Password");
}
}
else
{
Response.Write("Login is incorrect.");
conn.Close();
}
}
參見[?什麼是一個NullReferenceException,我如何修復它(http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and如何解決這個問題)。 'Pass.ExecuteScalar()'返回'null',所以你不能在它上面調用'ToString()'。 – CodeCaster
試試這個:string Password =(string)Pass.ExecuteScalar()。ToString(); – Manoj
在不同的用戶下多次發佈相同的問題並不是一個好主意。 –