私はすでに新しいデータをデータベースに追加し、datagridview を介してそのデータベースを表示することができます。また、「追加」ボタンをクリックするたびに datagridview を更新するようにコマンドを実行します (データベースに新しいデータを追加します)。ただし、古いデータと新しいデータが重複しています。
新しいデータを追加して datagridview を更新した後の複製を示すスクリーンショットを次に示します。
上の画像では、ID「16」の重複データがあり、新しい値を入力してデータベースに挿入するたびに、新しい(現在の)値がデータベースに追加されますが、古い値が複製されます。したがって、プログラムを終了して、再度起動する必要があります。しかし、これを解決する他の方法はありますか (新しいデータをデータベースに追加してデータグリッドビューを更新した後に古いデータが複製されない)?
これが私のコードです:
private void ViewDatabase(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT * FROM [Table]";
conn.Open();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
{
adapter.Fill(ds, "Table");
dataGridView1.DataSource = ds.Tables[0];
}
conn.Close();
}
}
private void Add(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "INSERT INTO [Table] ([ProductCode], [Quantity], [Description], [Price]) VALUES (@ProductCode, @Quantity, @Description, @Price)";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("@ProductCode", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters["@ProductCode"].Value = this.numericTextBox1.Text;
cmd.Parameters.Add("@Quantity", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters["@Quantity"].Value = this.numericUpDown1.Value;
cmd.Parameters.Add("@Description", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["@Description"].Value = this.textBox3.Text;
cmd.Parameters.Add("@Price", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters["@Price"].Value = this.textBox4.Text;
cmd.ExecuteNonQuery();
if (choice.comboBox1.Text == "English")
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav");
sound.Play();
DialogResult dialogResult = MessageBox.Show("Added Successfully!", "Success", MessageBoxButtons.OK);
if (dialogResult == DialogResult.OK)
{
ViewDatabase(sender, e);
ClearTextBoxes(sender, e);
}
}