Richard Richard - 2 months ago 18
C# Question

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

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();
}

Answer

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();

or

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

DataTable.Load

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.

Comments