Daniel Mitchell
Daniel Mitchell

Reputation: 105

How do you update a datagridview in C# every minute

I am working on a project in C# at the moment which is quite simple.

I have a status box, two buttons and a dataGridView.

When the Form loads the dataGridView is filled correctly.

What I would like to do is then update that table every 45 seconds to reflect any changes in the database.

I am looking for suggestions on a technique to achieve this. I have been searching for clear information but it seems somewhat lacking.

Upvotes: 5

Views: 13477

Answers (5)

Babak Fakhriloo
Babak Fakhriloo

Reputation: 2126

you mean that i should bind datagridview again in Timer event handler ?

Upvotes: 0

Daniel LeCheminant
Daniel LeCheminant

Reputation: 51081

  1. Add a Timer control to your form. (It's in the components category)
  2. Set its Interval property to 45000 (the value represents milliseconds)
  3. Either set the Enabled property of the timer to True in the form designer, or somewhere in your code.
  4. Add a handler for the timer's Tick event (you can get this by double-clicking the timer)
  5. Inside the Tick handler, update your dataGridView

Your handler will look like this:

private void timer1_Tick(object sender, EventArgs e)
{
    // Update DataGridView
}

If you need to suspend updates for some reason, you can call timer1.Stop() to stop the timer from running, and use timer1.Start() to start it up again.

Upvotes: 8

BFree
BFree

Reputation: 103740

Like others have suggested, use a Timer to requery the Database. The only thing I'd like to add is that when you re-query the database, don't just set the DataGridView's datasource to the new table. Rather, Merge it with the existing table. The reason for this is because if the user is in middle of the grid for example looking at a particular row, if you reset the DataSource to a new table, the entire grid will refresh and they will lose their place. Annoying as hell! If you merge it though, it will be seamless to the user.

DataTable.Merge

The one thing to be aware when using the Merge method is that the table needs to have a primary key. Double check to make sure that the DataTable itself has a primary key. Not always does it pull it back from the database. You may need to do something like:

table.PrimaryKey = new DataColumn[] {table.Columns["ID"]};

Upvotes: 5

Andy
Andy

Reputation: 30418

You could create a Timer that fires every 45 seconds, and update your UI from its event handler.

Upvotes: 1

TheTXI
TheTXI

Reputation: 37885

Use a timer control and then perform your updates at the specific increments you need.

Upvotes: 1

Related Questions