2016-12-08 4 views
0

これは初めての投稿です。 C#を使用してデータベースから行を削除する適切な方法を探しています。私はすでにdatagridviewから削除するコードを書いていますが、completleyに追加してデータベースから削除するものは何ですか?ここでMYSQLを使用してC#でデータベースから行を削除する

は、これまでのコードです:

foreach (DataGridViewRow row in dataGridView1.SelectedRows) 
{ 
    if (!row.IsNewRow) 
    { 
     dataGridView1.Rows.Remove(row); 
    } 

    MessageBox.Show("Selected rows Deleted"); 
} 

これは検索経由でだろうと考え、私が最初に試してみたものです:

OpenConnection(); 
string productType = txtDeleteProduct.Text; 
MainForm frm = new MainForm(); 
mySqlDataAdapter = new MySqlDataAdapter("DELETE * from products  WHERE ProductType= '@productType';", connection); 
DataSet DS = new DataSet(); 
mySqlDataAdapter.Fill(DS); 
dataGridView1.DataSource = DS.Tables[0]; 
CloseConnection(); 
+0

AFAIK 'DataGridView.Rows.Remove'は、DBではなく、データセットから項目を削除します。選択した行を削除するにはSQLコマンドを含め、実行するには 'ExecuteNonQuery'メソッドを使用する必要があります。 –

+0

[MySQLCommandBuilder](https://dev.mysql.com/doc/dev/connector-net/html/T_MySql_Data_MySqlClient_MySqlCommandBuilder.htm)を使用する必要があります。これはMySQLCommandBuilderについての[今質問です](http://stackoverflow.com/questions/11336843/update-datatable-to-mysql-database-c-sharp)です。たぶんあなたを助けることができます。 – Hermanto

答えて

0

これがあなたの第二の試料の適応であります:

using (var cn = new MySqlDbConnection("your connection string here")) 
using (var cmd = new MySqlDbCommand("DELETE * from products WHERE ProductType= @productType;")) // Note that I removed the single quotes (') 
{ 
    //Use the actual column type and length here. 
    // Ignore examples elsewhere online that use AddWithValue(). This is better! 
    cmd.Parameters.Add("@productType", MySqlDbType.VarString, 25).Value = txtDeleteProduct.Text; 
    cn.Open(); 
    cmd.ExecuteNonQuery(); 
} 

私はこれを完全に終了するための十分な情報がありません。そのようなものが必要ですが、実際のテーブル名とSQL文のキーフィールドが必要です。ここではもう少し近くに何かされています

using (var cn = new MySqlDbConnection("your connection string here")) 
using (var cmd = new MySqlDbCommand("DELETE * from `MYTABLE` WHERE MyIDColumn = @rowKey;")) // Note that I removed the single quotes (') 
{ 
    cmd.Parameters.Add("@rowKey", MySqlDbType.Int32); 
    cn.Open(); 

    foreach (DataGridViewRow row in dataGridView1.SelectedRows) 
    { 
     if (!row.IsNewRow) 
     { 
      //not sure which cell(s) in the grid make up your primary key 
      cmd.Parameters["@rowKey"].Value = Convert.ToInt32(row.Cells[0]); 
      cmd.ExecuteNonQuery(); 
      dataGridView1.Rows.Remove(row); 
     }   
    }  
} 
MessageBox.Show("Selected rows Deleted"); 

は最後に...ここで、通常の手順では、最初からすべてをリロード...再バインドグリッドその後、削除コマンドを送信するために実際にある、と。グリッドを読み込むコードをすでに持っているのでこれを行うので、少しのコード作業が省け、その間にテーブル内の何かが変更された場合に更新する機会が与えられます。

関連する問題