Scenario : i have a database table that is being updated frequently by some services.
I have a c# Winforms Application that load this table in a datagridview by binding a datatable as Datasource, then i whant to add a Timer that every 10 seconds update a the content of a datatable with the last changes in the database table …
I don’t need to update a database with the datatable changes, but i need to update datatable with the last changes in the database table, that is the inverse of the usually….
Is there a way to do that ? What is the best way ?
i’ve tried with this code :
private void ServiceTimer_Tick(object state)
{
OdbcConnection oCon = new OdbcConnection();
oCon.ConnectionString = ConnectionStrings;
OdbcDataAdapter dp = new OdbcDataAdapter("SELECT * FROM table", oCon);
dsProva.Tables.Clear();
dp.Fill(dsProva,"table");
dataGridViewMessaggi.DataSource = dsProva.Tables["table"];
dataGridViewMessaggi.Refresh();
}
But every Timer Tick i lost the selection in DatagridView and Current Row ….
Is There a better solution ?
Before updating the data grid, you will need to store all the current selections you are interested in and then restore them once the new data binding has completed.
The CurrentRow, you can get from the BindingContext. For example
Then to restore the current row after rebinding the DGV
Of course this will only ensure the current row is pointing to the same row index, which if your data has changed enough might not be the same data row as before.
If you want to have the same row interms of data selected, you can can use the key of the row and loop through the data and once you find the index of the row that matches the previous selection you can set the binding context to that index.