I have a datagrid that displays a table which is bound to a SQL server DB. I would like to set a Timer for every 60 sec, that checks for any update and then displays the latest updated data.
So far I have created an event_handler for datagrid, that includes the object dispatcher timer
private void dataGrid1_loaded(object sender, RoutedEventArgs e)
{
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 60);
dispatcherTimer.Start();
}
Now I don't know how to proceed further with the event handler to handle the newly updated data from the database.
dispatcherTimer_Tick
Here is my select statement that is used to fill the datagrid.
private void Page_Loaded(object sender, RoutedEventArgs e)
{
try
{
String selectstatement = "select top 2 ItemID, ItemName,ConsumerName, Street, DOJ from ConsumarTB order by ItemID ";
da = new SqlDataAdapter(selectstatement, con);
ds = new DataSet();
da.Fill(ds);
dataGrid1.ItemsSource = ds.Tables[0].DefaultView;
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
}
There are a lot of ways to improve what you have above. But here's what I would try for starters.
Below will populate your datagrid on page load, set a timer to tick every 60 seconds. When the timer ticks, it will call a method to load data to the grid again.
//On PageLoad, populate the grid, and set a timer to repeat ever 60 seconds
private void Page_Loaded(object sender, RoutedEventArgs e)
{
try
{
RebindData();
SetTimer();
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
}
//Refreshes grid data on timer tick
protected void dispatcherTimer_Tick(object sender, EventArgs e)
{
RebindData();
}
//Get data and bind to the grid
private void RebindData()
{
String selectstatement = "select top 2 ItemID, ItemName,ConsumerName, Street, DOJ from ConsumarTB order by ItemID ";
da = new SqlDataAdapter(selectstatement, con);
ds = new DataSet();
da.Fill(ds);
dataGrid1.ItemsSource = ds.Tables[0].DefaultView;
}
//Set and start the timer
private void SetTimer()
{
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 60);
dispatcherTimer.Start();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With