简体   繁体   English

WPF Datagrid-自动刷新

[英]WPF Datagrid- auto refresh

I have a datagrid that displays a table which is bound to a SQL server DB. 我有一个datagrid,显示一个绑定到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. 我想每隔60秒设置一个Timer,检查任何更新,然后显示最新的更新数据。

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

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. 下面将在页面加载时填充您的数据网格,将计时器设置为每60秒打勾一次。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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