如何在将数据插入数据库后刷新DataGridView? [英] How to refresh DataGridView after inserting data into database?
问题描述
大家好,我正在开发一个Windows应用程序。在一个表单中包含多个datagridivew,它显示mysql表中的表内容。在表单中,我有一个链接到另一个窗体的按钮,他们正在向表中插入值。插入后,当我点击保存按钮时,它应该保存在表格中,并且还会在datagridview中更新。
如果我在插入值后调用display()方法该表格显示N次。
Hi all, I am developing a windows application.In that one form contains multiple datagridivew which displays the table content from mysql table. In form i have button which links to another windows form and their i am inserting values to the table. After inserting when i click on Save button, it should save in the table and also updates in the datagridview.
If i call the display() method after inserting values to the table, it is displaying N number of times.
public void display()
{
try
{
connection = new MySqlConnection(connection_string);
connection.Open();
//Code to Display Customer Details in Home Page
dataAdapter_Customer=new MySqlDataAdapter(string.Format("select cusname,balance, contact, phone1,email from new_customer where busname=?p1"),connection);
dataAdapter_Customer.SelectCommand.Parameters.AddWithValue("?p1", busnamevar);
commandBuilder_Customer=new MySqlCommandBuilder(dataAdapter_Customer);
dataTable_Customer.Locale=System.Globalization.CultureInfo.InvariantCulture;
dataAdapter_Customer.Fill(dataTable_Customer);
bindingSource=new BindingSource();
bindingSource.DataSource=dataTable_Customer;
dataGridView1.DataSource=bindingSource;
//Code to Display Supplier Details in Home Page
dataAdapter_Supplier = new MySqlDataAdapter(string.Format("select suppliername,total_balance,contact,phone1,email from new_supplier where businessname=?p1"), connection);
dataAdapter_Supplier.SelectCommand.Parameters.AddWithValue("?p1", busnamevar);
commandBuilder_Supplier = new MySqlCommandBuilder(dataAdapter_Supplier);
dataTable_Customer.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter_Supplier.Fill(dataTable_Supplier);
bindingSource1 = new BindingSource();
bindingSource1.DataSource = dataTable_Supplier;
dataGridView3.DataSource = bindingSource1;
connection.Close();
}
catch(MySqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
如果表包含4行,当我调用display()方法时,它是显示8行,就像我点击刷新按钮时一样增加。
我想我必须在显示内容后清理。
If the table contains 4 rows, when i call display() method, it is showing 8 rows, like that it is increasing when ever i click on refresh button.
I think i have to clean after displaying the contents.
推荐答案
在使用网格视图绑定之前,使用NULL重置网格视图。
Before binding with Grid view, reset the Grid view with NULL.
你可以把
Gridview.datasource = null;
Gridview.Databind();
....
YOu can put
Gridview.datasource = null;
Gridview.Databind();
after you insert the data to database....
如你所说的那样在窗口应用上工作。
你可以使用
Hi,
as you said you are working on window app.
you can use
dataGridView1.Rows.Clear();
。
before binding gridview.
这篇关于如何在将数据插入数据库后刷新DataGridView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!