我已经可以将新数据添加到数据库并通过datagridview显示该数据库,并且每当我单击“添加”按钮(将新数据添加到数据库)时,我都会命令刷新datagridview。但它与新数据重复旧数据。
这是添加新数据并刷新datagridview后显示重复的屏幕截图:
在上图中,ID“16”的重复数据,每当我输入新值并将其插入数据库时,它会将新(当前)值添加到数据库中,但旧值将被重复。因此,我必须退出该程序并重新启动它。但是,有没有其他方法可以解决这个问题(将新数据添加到数据库并刷新 datagridview 后旧数据不重复)?
这是我的代码:
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);
}
}