Ivan Ivan - 3 months ago 25
MySQL Question

Refresh button duplicate the datagridview data

I have problem when i try to refresh data in

datagridview
. Am using
MySQL
database. On every click on
Reload
button my old data is duplicated in grid. I try to set
datagridview.DataSource = null
also try to
Refresh
datagrid and also try to
Resert
binding source but nothing is happening.

Check this:

enter image description here

public MainForm()
{
InitializeComponent();
this.connStr = Properties.Settings.Default.connStr;
}

// Load
private void Form1_Load(object sender, EventArgs e)
{
SelectData();
}

// Seslect Data
public void SelectData()
{
bs.DataSource = GetData("SELECT * FROM porudzbine");
dataGridView1.DataSource = bs;
}

// Get Data
private DataTable GetData(string query)
{
try
{
conn = new MySqlConnection(connStr);
conn.Open();
adapter = new MySqlDataAdapter(query, conn);
adapter.Fill(dt);
}
catch(MySqlException ex)
{
MessageBox.Show(ex.Message.ToString());
}

return dt;
}

// Reload
private void osveziListuPorudzbinaButton_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = null;
dataGridView1.Refresh();
bs.ResetBindings(false);
bs.DataSource = GetData("SELECT * FROM porudzbine");
dataGridView1.DataSource = bs;
}

Answer

You have a field called dt somewhere in your form (not shown in the post), which you are refilling (hence adding the records to the previously loaded records) on each GetData call.

Remove the field and use something like this:

// Get Data
private DataTable GetData(string query)
{
    var dt = new DataTable();
    // ...
    return dt;
}