简体   繁体   中英

How do I refresh DataGridView?

I have a button that updates the data in datagridview but I have to start the form again for changes to show. How do I make so that my datagridview will update itself after I click the button?

Here's the code for my datagridview in case anyone needs it:

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

As the DataGridView is bounded to the DataTable, any change in the DataTable will be automatically displayed in the DataGridView.

If you need to repeat the Fill command, set the DataSource to null before the fill and restore it after :

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

Put your code in a function and call it when you open the form or when you click the button.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM