2014-07-12 39 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"; 
} 
相關問題