2014-05-10 43 views
-7

當我運行代碼,並且我輸入了錯誤的用戶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(); 
     } 


    } 
+1

參見[?什麼是一個NullReferenceException,我如何修復它(http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and如何解決這個問題)。 'Pass.ExecuteScalar()'返回'null',所以你不能在它上面調用'ToString()'。 – CodeCaster

+0

試試這個:string Password =(string)Pass.ExecuteScalar()。ToString(); – Manoj

+1

在不同的用戶下多次發佈相同的問題並不是一個好主意。 –

回答

0

ExecuteScalar()將返回null,並且null.ToString()是無效的。而不是嘗試

string Password = Pass.ExecuteScalar() as string; 

如果由於任何原因導致結果無法轉換爲字符串,那麼將Password設置爲null。或者:

string Password =(string)Pass.ExecuteScalar(); 

不同之處在於'as string'會容忍另一種類型(如整數),並只會在這種情況下爲null。而'(字符串)'將拋出一個異常,如果該值不是字符串或null。

-1

這將工作:

string Password =(string)Pass.ExecuteScalar().ToString(); 
+0

當然'string Password =(string)Pass.ExecuteScalar();'夠了嗎? – user826840

+0

不,它不會,當查詢沒有返回結果時,'Pass.ExecuteScalar()'返回'null'。 – CodeCaster

+0

no still same error – user3622983

相關問題