-1

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.デザイナー

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

2 に答える 2

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;
            }
        }
    }
}
于 2012-10-12T23:34:24.453 に答える
1

私はローレンスに同意します

接続文字列セクションは次のようになります。

<configuration> 
    <connectionStrings>
        <add name="modelConnectionString" connectionString="whatever" providerName="System.Data.SqlClient" />
    </connectionStrings>
 <!-- more stuff here-->
于 2012-10-12T23:47:41.793 に答える