datagridview を使用してデータベースを更新したかったのですが、既に編集できますが、データベースに更新されませんでした。
どうすれば修正できますか?
これが私のコードです:
私のフォームにはボタンがあります.1つは「EditingDatabase」関数を参照する「編集」ボタンで、もう1つはデータベースにデータを更新する「OK」ボタンです(コードはこれにあります以下のコードでは、コードで言及しています)。
private void EditingDatabase(object sender, EventArgs e)
{
DataTable _dt = (DataTable)dataGridView1.DataSource;
if (_dt.DefaultView.Count > 0)
{
int rowNum = dataGridView1.CurrentRow.Index;
int productCode = Convert.ToInt32(_dt.DefaultView[rowNum]["ProductCode"]);
int quantity = Convert.ToInt32(_dt.DefaultView[rowNum]["Quantity"]);
int price = Convert.ToInt32(_dt.DefaultView[rowNum]["Price"]);
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string commandSelect = "SELECT [Quantity], [Price] FROM [Table] WHERE [ProductCode] = @ProductCode";
string commandUpdate = "UPDATE [Table] SET [Quantity] = @Quantity, [Price] = @Price WHERE [ProductCode] = @ProductCode";
conn.Open();
using (OleDbCommand _cmdSelect = new OleDbCommand(commandSelect, conn))
using (OleDbCommand _cmdUpdate = new OleDbCommand(commandUpdate, conn))
{
_cmdSelect.Parameters.Add("@ProductCode", System.Data.OleDb.OleDbType.Integer);
_cmdSelect.Parameters["@ProductCode"].Value = productCode;
_cmdUpdate.Parameters.Add("ProductCode", System.Data.OleDb.OleDbType.Integer);
_cmdUpdate.Parameters.Add("@Quantity", System.Data.OleDb.OleDbType.Integer);
_cmdUpdate.Parameters.Add("@Price", System.Data.OleDb.OleDbType.Integer);
using (OleDbDataReader dReader = _cmdSelect.ExecuteReader())
{
while (dReader.Read())
{
_cmdUpdate.Parameters["@ProductCode"].Value = productCode;
_cmdUpdate.Parameters["@Quantity"].Value = quantity;
_cmdUpdate.Parameters["@Price"].Value = price;
int numberOfRows = _cmdUpdate.ExecuteNonQuery();
}
dReader.Close();
}
}
conn.Close();
}
if (_choice.comboBox1.Text == "English") // THIS IS WHERE THE "OK" BUTTON FUNCTION RUNS
{
System.Media.SoundPlayer _sounds = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav");
_sounds.Play();
MessageBox.Show("Updated Successfully!", "Updated");
ShowButtons(sender, e);
DisableColumnEdited(sender, e);
}
}
else
{
if (_choice.comboBox1.Text == "English")
{
System.Media.SoundPlayer _sounds = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav");
_sounds.Play();
MessageBox.Show("There is no Data in the Selected Row!", "Error");
return;
}
}
}
編集済み
以下は、プログラム内の私の datagridview のスクリーンショットです。datagridview は、次の名前のデータベース テーブルに接続されていますTable
。
ありがとうございました。
あなたの答えに感謝します!