WPF Datagrid-自动刷新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13992107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Datagrid- auto refresh
提问by Indhi
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.
我有一个显示绑定到 SQL 服务器数据库的表的数据网格。我想每 60 秒设置一个计时器,检查任何更新,然后显示最新更新的数据。
So far I have created an event_handler for datagrid, that includes the object dispatcher timer
到目前为止,我已经为 datagrid 创建了一个 event_handler,其中包括对象调度程序计时器
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.
这是我用来填充数据网格的 select 语句。
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);
}
}
回答by Khan
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.
下面将在页面加载时填充您的数据网格,将计时器设置为每 60 秒打勾一次。当计时器滴答作响时,它会调用一个方法再次将数据加载到网格中。
//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();
}

