我有一个更新datagridview中数据的按钮,但我必须再次启动表单以显示更改。单击按钮后,如何使我的datagridview自动更新?
这是我的datagridview的代码,以防有人需要它:
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from Customer";
command.CommandText = query;
OleDbDataAdapter DA = new OleDbDataAdapter(command);
DT = new DataTable();
DA.Fill(DT);
dataGridView1.DataSource = DT;
connection.Close();
答案 0 :(得分:0)
当DataGridView与DataTable绑定时,DataTable中的任何更改都将自动显示在DataGridView中。
如果需要重复填充命令,请在填充之前将DataSource设置为null,并在之后将其恢复:
dataGridView1.DataSource = null;
DT.Clear() ;
DA.Fill(DT);
dataGridView1.DataSource = DT;
答案 1 :(得分:0)
将代码放入函数中,并在打开表单或单击按钮时调用它。
private void Form1_Load(object sender, EventArgs e)
{
RefreshGrid();
}
private void button1_Click(object sender, EventArgs e)
{
RefreshGrid();
}
void RefreshGrid()
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from Customer";
command.CommandText = query;
OleDbDataAdapter DA = new OleDbDataAdapter(command);
DT = new DataTable();
DA.Fill(DT);
dataGridView1.DataSource = DT;
connection.Close();
}