2014-07-12 115 views
2

每2分钟所以我创建用户控件用的dataGridView,我实际上将如何对象是次要的,但让我们说我有alredy数据源,我想刷新的dataGridView这些值。如何调用函数的用户控件在.NET 3.5

的例子,我有功能fillDataGridView(),我想每2分钟

我认为我可以用Thread类中做到这一点,但它叫W/O任何成功还

如何你处理UI刷新?

我知道这看起来像“但与UI更新问题另一个人”,但是从我所看到的我真的不是最简单的办法做到这一点

public partial class Alertbox : UserControl 
{ 
    private static System.Timers.Timer aTimer; 

    public Alertbox() 
    { 
     InitializeComponent(); 

     aTimer = new System.Timers.Timer(10000); 

     aTimer.Elapsed += new ElapsedEventHandler(Update); 

     aTimer.Interval = 2000; 
     aTimer.Enabled = true; 
    } 

    public void Update(object source, ElapsedEventArgs e) 
    { 
     BT_AddTrigger.Text += "test"; // append to button text 
    } 
} 

它喊这么

System.Windows.Forms.dll中发生类型'System.InvalidOperationException'异常,但未在用户代码中处理其他 信息:跨线程操作无效:控制'BT_AddTrigger' 从非线程访问它创建的线程。

+0

为了防止错扣,使用:'BT_AddTrigger.Invoke(新行动(UpdateButtonText),新的对象[] {文本});'喜欢这里:HTTPS:/ /gist.github.com/PopovMP/8f747dbd6948eccc69ad。但是,更好的选择是使用'System.Windows.Forms.Timer',因为你在UserControl中。 –

回答

-1

您应该使用定时器类这样

  System.Timers.Timer testTimer = new System.Timers.Timer(); 
      testTimer.Enabled = true; 
      //testTimer.Interval = 3600000; //1 hour timer 
      testTimer.Interval = 100000;// Execute timer every // five seconds 
      testTimer.Elapsed += new System.Timers.ElapsedEventHandler(FillGrid); 
+0

在哪里调用? –

+0

有几个问题在这里:1.跨线程调用的WinForms控制,2,必须设置'testTimer.AutoReset = TRUE',3'testTimer.Interval = 100000;'为100秒。 –

5

使用System.Windows.Forms.Timer而不是System.Timer.Timer。

由于System.Timer.Timer运行在不同的线程上,并且无法在不调用Control.Invoke()的情况下从另一个线程调用WinForms线程上的操作,您会得到Cross Thread Operation Not Valid错误。

System.Windows.Forms.Timer将使用相同的线程的UI,你会避免这些问题。

+0

这里是不同定时器类的.NET中的详细的比较:http://msdn.microsoft.com/en-us/magazine/cc164015.aspx –

1

您可以使用System.Windows.Forms

using System.Windows.Forms; 

public Alertbox() 
{ 
    InitializeComponent(); 

    var timer = new Timer {Interval = 2*60*1000}; 
    timer.Tick += Timer_Tick; 
    timer.Start(); 
} 

void Timer_Tick(object sender, EventArgs e) 
{ 
    BT_AddTrigger.Text += "test"; 
} 
相关问题