2016-10-16 10 views
0

データベースの更新中に問題が発生しました。エラー接続が閉じられます。問題がどこにあるのかわかりません。私はconnection.openを開始しましたが、動作していません。SQL Serverデータベースの更新

public void btnUpdate_Click(object sender, EventArgs e) 
{ 
    if (txtName.Text != "" && txtRollNo.Text != "" && txtRegdNo.Text != "" && txtProgram.Text != "" && txtValidity.Text != "" && pBoxPhoto.Image != null && pBoxQR.Image != null) 
    { 
     scommand = new SqlCommand("update tblRegistration set [email protected],[email protected],[email protected],[email protected],[email protected], [email protected] where [email protected]", connection); 

     scommand.Parameters.AddWithValue("@id", txtID.Text); 
     scommand.Parameters.AddWithValue("@name", txtName.Text); 
     scommand.Parameters.AddWithValue("@program", txtProgram.Text); 
     scommand.Parameters.AddWithValue("@regdno", txtRegdNo.Text); 
     scommand.Parameters.AddWithValue("@rollno", txtRollNo.Text); 
     scommand.Parameters.AddWithValue("@validity", txtValidity.Text); 
     scommand.Parameters.AddWithValue("@address", txtAddress.Text); 

     connection.Open(); 
     sCommand.ExecuteNonQuery(); 

     MessageBox.Show("Record Updated Successfully"); 
     clearData(); 
     dataGridView1.DataSource = null; 
     fillData(); 

     connection.Close(); 
     clickable(); 
    } 
    else 
    { 
     MessageBox.Show("Please Provide Details!"); 
    } 
} 

私が間違っているところを教えてください。前もって感謝します。廃棄がある(

using (var connection = new SqlConnection()) 
{ 
    // perform Sql Command using the connection 
} 

あなたがusingを使用するので、範囲から出た、Disposeメソッドが自動的に呼び出されます:

Error Message

+1

毎回新しい接続を使用する必要があります。同じ接続を再利用しようとはしません。 DataTableとDataAdapterを使用する場合は、 'dataGridView1.DataSource = null;でDGVを上回らなければなりません。 – Plutonix

+0

usingステートメントを使用して接続を切断します。 – inan

+1

1.データベース接続がオープンしていません。 2.パラメータ値を固有の型で含める必要があります。 idがデータベースの整数の場合は、.net int/Int32を使用して値を追加します。 3.必要なときにado.netタイプを作成して 'using'ステートメントで処理します。これらのインスタンスをメソッド/クラス間で共有しないでください。 [ベストプラクティス - SQL文を実行する]を参照してください。(0120-18753) – Igor

答えて

0

のSqlConnectionクラスでIDisposableを、それを使用するため、neatest方法を実装しますそのクラスのCloseに相当)。

+0

を実行してください。新しいエラーが発生しました。QRCARD.exeで 'System.NullReferenceException'型の未処理例外が発生しました。 追加情報:オブジェクト参照がオブジェクトのインスタンスに設定されていません。 – Sdp

+0

'SqlConnection'には異なるコンストラクタがありますので、前に使っていたものと同じものを使用してください(例えば' new SqlConnection( "私の気の利いたSQL接続.."); ' – peval27

+0

申し訳ありません:-( – Sdp

関連する問題