如何刷新DataGridView

本文关键字:DataGridView 刷新 何刷新 | 更新日期: 2023-09-27 18:06:27

我有一个按钮,更新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();

如何刷新DataGridView

将代码放入函数中,并在打开表单或单击按钮时调用它。

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();
}

由于DataGridView与数据表绑定,数据表的任何变化都将自动显示在DataGridView中。

如果您需要重复填充命令,请在填充之前将DataSource设置为null,并在填充之后恢复它:

    dataGridView1.DataSource = null;
    DT.Clear() ;
    DA.Fill(DT);
    dataGridView1.DataSource = DT;