2014-05-08 73 views
-7

我已將代碼更改爲此代碼,但現在我得到的另一個問題是未將對象引用設置爲對象的實例。錯誤是:我得到的對象引用未設置爲對象的實例

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."); 
    } 
} 
+2

哪一行有錯誤? –

+0

你甚至不知道問題出在哪裏,這是你所指的對象...... – Lynx

+4

'ExecuteScalar'可以返回'null'。 'txt_userID'也是'TextBox'。我建議在查詢中使用參數並傳遞'txt_userID.Text'而不是'txt_userID'。 –

回答

2

你最好不要做這樣的事情......

var Password = Pass.ExecuteScalar(); 

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

通過調用一個object這可能是null.ToString().Replace()等,你會得到這個例外。

這裏的行if (temp != 1)需要是(temp != 0),因爲如果它沒有找到用戶,您將輸入該代碼塊。如果以前的結果爲0,則IF語句中的下一個SQL查詢將找不到用戶。所以,Password將是null,因此錯誤。

此外,作爲一個側面說明,以幫助防止SQL Injection

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

我有一個嘮叨的感覺,IF語句應該是'if(temp == 1)',以防萬一重複的用戶名進入數據庫的某些方式。當然,這不會解決所有安全問題,您應該查看安全威脅。 – JasonMArcher

+0

@JasonMArcher,我同意數據庫應該只有一個條目,但爲了這個問題,它絕對不應該是'!= 1',因爲這將不允許記錄。 – christiandev

相關問題