我有一个datagrid,显示一个绑定到sql Server DB的表.
我想每隔60秒设置一个Timer,检查任何更新,然后显示最新的更新数据.
我想每隔60秒设置一个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,60); dispatcherTimer.Start(); }
现在我不知道如何继续使用事件处理程序来处理数据库中新更新的数据.
dispatcherTimer_Tick
这是我用于填充数据网格的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); } }
解决方法
有很多方法可以改善你的上述内容.但这是我会为初学者尝试的.
下面将在页面加载时填充您的数据网格,将计时器设置为每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,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,60); dispatcherTimer.Start(); }