Everytime when I add a new row to my datagridview I get duplicated rows from the rows that I added before the current one. I am using an external mysql database.
private void FillTable()
{
try
{
MySqlConnection DBConn = new MySqlConnection(MysqlConnectionString);
MySqlCommand Command = new MySqlCommand("SELECT DISTINCT Voornaam, Achternaam, Leeftijd, GBDag, GBMaand, GBJaar, Adres, Woonplaats, Postcode FROM Libra_Klanten ORDER BY Voornaam", DBConn);
MySqlDataAdapter Adapter = new MySqlDataAdapter(Command.CommandText, DBConn);
MySqlCommandBuilder Builder = new MySqlCommandBuilder(Adapter);
DBConn.Open();
Command.ExecuteNonQuery();
Adapter.Fill(CustomersTable);
CustomersDataViewer.DataSource = CustomersTable;
CustomersDataViewer.DataMember = CustomersTable.TableName;
CustomersDataViewer.AutoResizeColumns();
DBConn.Close();
DBConn.Dispose();
Command.Dispose();
Adapter.Dispose();
Builder.Dispose();
}
catch (Exception Ex)
{
Debug.WriteLine(Ex.Message);
}
}
And this is the code for the insert statement:
private void ButtonInsertCustomer_Click(object sender, EventArgs e)
{
if (TextBoxVoornaam.TextLength > 0 && TextBoxAchternaam.TextLength > 0 && NumLeeftijd.Value > 0 && DateGeboorteDatum.Value != null && TextBoxAdres.TextLength > 0 && TextBoxWoonplaats.TextLength > 0 && TextBoxPostcode.TextLength > 0)
{
try
{
MySqlConnection DBConn = new MySqlConnection(MysqlConnectionString);
MySqlCommand Command = new MySqlCommand("INSERT INTO Libra_Klanten (Voornaam, Achternaam, Leeftijd, GBDag, GBMaand, GBJaar, Adres, Woonplaats, Postcode) values ('" + TextBoxVoornaam.Text + "','" + TextBoxAchternaam.Text + "','" + NumLeeftijd.Value + "','" + DateGeboorteDatum.Value.Day + "','" + DateGeboorteDatum.Value.Month + "','" + DateGeboorteDatum.Value.Year + "','" + TextBoxAdres.Text + "','" + TextBoxWoonplaats.Text + "','" + TextBoxPostcode.Text + "')", DBConn);
DBConn.Open();
Command.ExecuteNonQuery();
DBConn.Close();
DBConn.Dispose();
Command.Dispose();
FillTable();
}
catch (MySqlException ex)
{
Debug.WriteLine(ex.Message);
}
}
else
{
MessageBox.Show("Vul alle velden in.");
}
}
Each time I insert a new customer to the database a duplicate shows up from the previous rows that I added. I already tried to use .Clear() on the datagridview but that didn't work.
CustomersTable.Clear();at the beginning of yourFillTablemethod? Clearing the datagridview won't remove the previous data, you need to clear its datasource. - ChawinCustomersDataViewer.DataSource = Nullthen make sure to callCustomersDataView.Clear()orCustomersDataView.RowCount = 0to remove all the rows. - Chawin