每当我向datagridview添加一个新行时,我都会从当前添加的行中获取重复的行。我正在使用外部mysql数据库。
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);
}
}
这是insert语句的代码:
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.");
}
}
每次我将新客户插入数据库时,都会显示我添加的前一行的副本。我已经尝试在datagridview上使用.Clear()
,但这不起作用。
答案 0 :(得分:0)
由于您的datagridview绑定到数据源,您需要清除数据源本身。
在CustomersTable.Clear();
方法的开头运行FillTable
,以确保您的数据源中没有数据; datagridview将反映这一点。