How to Reload DataGridView using DataTable.Load(DataReader) without duplicate records

Can anyone help me on how to avoid getting duplicated output on DataGridView. Here is the image Before change and the image After add/edit or delete.

Here is the loader for my DataGridView:

private DataTable data() { using (OleDbConnection con = new OleDbConnection(inventorydb)) { using (OleDbCommand com = new OleDbCommand("Select * FROM Items",con)) { con.Open(); OleDbDataReader reader = com.ExecuteReader(); items.Load(reader); } } return items; } void reset() { connect.Close(); connect.ConnectionString = inventorydb; connect.Open(); dataGridView1.DataSource = null; dataGridView1.Update(); dataGridView1.Refresh(); dataGridView1.DataSource = data(); }

Add and save changes:

private void save_Click(object sender, EventArgs e) { if (mode == "a") { connect.Close(); connect.ConnectionString = inventorydb; connect.Open(); sqlcommand.CommandText = "INSERT INTO Items (SerialID, Brand_Name, Item_Name,Item_Date) VALUES ('" + txtserial.Text + "','" + txtbrand.Text + "', '" + txtitem.Text + "', '" + date + "') "; sqlcommand.Connection = connect; OleDbDataReader reader = sqlcommand.ExecuteReader(); MessageBox.Show("Record(s) Saved", "Sample"); } connect.Close(); reset(); }


DataTable.Load adds result to the existing rows by default. So if you need to just have latest records, before calling DataTable.Load, you should clear the DataTable, otherwise the new result will be merged with existing rows.

So with your items variable which is DataTable, you can use either of these options:

items= new DataTable();


items.Clear(); items.AcceptChanges();


Fills a DataTable with values from a data source using the supplied IDataReader. If the DataTable already contains rows, the incoming data from the data source is merged with the existing rows.

人吐槽 人点赞



用户名: 密码:
验证码: 匿名发表


查看评论:How to Reload DataGridView using DataTable.Load(DataReader) without duplicate records