按钮单击抛出System.NullReferenceException

时间:2012-10-12 23:29:24

标签: c# .net

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);

2 个答案:

答案 0 :(得分:2)

逐步调试调试器中的代码,找出引发异常的行以及哪个对象为null。

此外,您应该重构代码以使用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;
            }
        }
    }
}

答案 1 :(得分:1)

我同意劳伦斯

连接字符串部分应如下所示:

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