2012-10-12 103 views
-1

System.NullReferenceException:未設置爲一個對象的實例對象引用。按鈕點擊引發System.NullReferenceException

單擊按鈕時,我收到該錯誤。 。
Form1類:

private void button1_Click(object sender, EventArgs e) 
    { 
     string connectionString = ConfigurationManager.ConnectionStrings["modelConnectionString"].ConnectionString; 
     SqlConnection sqlConnection = new SqlConnection(connectionString); 
     sqlConnection.Open(); 
     SqlCommand connect = new SqlCommand("SELECT COUNT(*) From Users WHERE UserName = @user AND Password = @pass", sqlConnection); 
     SqlParameter username = connect.Parameters.AddWithValue("@user", userName.Text); 
     SqlParameter password = connect.Parameters.AddWithValue("@pass", passWord.Text); 

     if ((int)connect.ExecuteScalar() == 1) 
     { 
      accessPic.BackgroundImage = Res.Accepted; 
     } 
     else 
     { 
      accessPic.BackgroundImage = Res.Denied; 
     } 
     sqlConnection.Close(); 
    } 

Form1.Designer

 // 
     // button1 
     // 
     this.button1.Location = new System.Drawing.Point(95, 90); 
     this.button1.Name = "button1"; 
     this.button1.Size = new System.Drawing.Size(75, 25); 
     this.button1.TabIndex = 8; 
     this.button1.Text = "button1"; 
     this.button1.UseVisualStyleBackColor = true; 
     this.button1.Click += new System.EventHandler(this.button1_Click); 
+0

哪條線給你的錯誤? – xxbbcc

+0

你可以在調試模式下運行這個命令,看看哪個語句出現這個錯誤嗎?我懷疑這是第一行的連接字符串調用。 – Laurence

+0

使用調試器查看引發異常的位置。我假設userName,passWord或accessPic爲空。 –

回答

2

步驟通過在調試器的代碼以找到線拋出異常且對象爲空。

此外,您應該重構代碼以使用using以確保在完成連接後處理連接。如果在打開和關閉連接之間拋出異常,現有的代碼將不會關閉連接。這裏是如何做到這一點:

private void button1_Click(object sender, EventArgs e) 
{ 
    string connectionString = ConfigurationManager.ConnectionStrings["modelConnectionString"].ConnectionString; 
    using (SqlConnection sqlConnection = new SqlConnection(connectionString)) 
    { 
     sqlConnection.Open(); 
     using (SqlCommand connect = new SqlCommand("SELECT COUNT(*) From Users WHERE UserName = @user AND Password = @pass", sqlConnection)) 
     { 
      SqlParameter username = connect.Parameters.AddWithValue("@user", userName.Text); 
      SqlParameter password = connect.Parameters.AddWithValue("@pass", passWord.Text); 

      if ((int)connect.ExecuteScalar() == 1) 
      { 
       accessPic.BackgroundImage = Res.Accepted; 
      } 
      else 
      { 
       accessPic.BackgroundImage = Res.Denied; 
      } 
     } 
    } 
} 
+0

原來我拼錯了連接字符串。 –

1

我勞倫斯

連接字符串部分應該是這樣的認同:

<configuration> 
    <connectionStrings> 
     <add name="modelConnectionString" connectionString="whatever" providerName="System.Data.SqlClient" /> 
    </connectionStrings> 
<!-- more stuff here-->