2015-10-19 70 views
2

我有一個WinForms應用程序,我使用DataGridView來顯示一些快速變化的數據。我使用間隔爲50-100毫秒的System.Windows.Forms.Timer()來限制DataSource的更新頻率,從而限制UI。 我希望能夠刪除網格中的行,所以我添加了DataGridViewButtonColumn,我通過CellContentClick事件處理。問題是,由於相當「高」的更新頻率,此事件並不一致。有時會發生,有時不會發生。 有沒有什麼辦法來解決這個問題,我在網格中保持按鈕,仍然使用快速的UI更新率(大約100毫秒)?快速刷新DataGridView中的按鈕點擊事件不一致觸發

這是我的代碼的精簡版:

private IBindingList _bindingList = new BindingList<MyData>(); 
private BindingSource _bindingSource = new BindingSource(_bindingList, null); 

private void Form1_Load(object sender, EventArgs e) 
{ 
    dataGridView.DataSource = _bindingSource; 

    var uiTimer = new System.Windows.Forms.Timer(); 
    uiTimer.Interval = 100; 
    uiTimer.Tick += uiTimer_Tick; 
    uiTimer.Start(); 
} 

private void uiTimer_Tick(object sender, EventArgs e) 
{ 
    // Get the underlying list of the binding source 
    var list = ((IList<MyData>)_bindingSource.List); 

    // Manipulate affected items in the bindinglist here... 

    // Update DataGridView 
    _bindingSource.ResetBindings(false); 

} 

private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e) 
{ 
    var senderGrid = (DataGridView)sender; 

    if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && 
      e.RowIndex >= 0) 
    { 
     MessageBox.Show("Button clicked!"); 
     // Do remove stuff here... 
    } 
} 
+1

我認爲最好不要將數據重新綁定到datagrid視圖,而應該更新數據網格視圖中的數據。您可能會發現[此答案](http://stackoverflow.com/a/33164169/3110834)和[這一個](http://stackoverflow.com/a/33163921/3110834)有幫助 –

+0

手動更新單元格招。有點乏味,但無論工程:o)非常感謝! – user3337693

+0

很高興聽到它幫助你解決了這個問題,在stackoverflow中,你可以通過點擊答案附近的向上箭頭來投票選擇儘可能多的答案,這樣對未來的讀者會更有用。 –

回答

0

一些想法......

  1. 代替_bindingSource.ResetBindings(假);

也許是其更有效地使用SuspendBinding/ResumeBinding組合

_bindingSource.SuspendBinding(); 
// affected items in the bindinglist here... 
_bindingSource.ResumeBinding(); 

還要確保_bindingList未在其他地方修改,但在定時器事件

  • [ 首選]使用反應性擴展代替計時器來緩衝更新http://www.introtorx.com/content/v1.0.10621.0/13_TimeShiftedSequences.html
  • +0

    不幸的是,第一個想法對這個問題沒有任何影響,但是謝謝你的建議。 – user3337693

    相關問題