2016-04-21 194 views
0

我有一個DataGridView我填滿它是這樣的:添加行的DataGridView太慢

private void FillDataGridView(string stringTable) 
{ 
    var lines = stringTable.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); 

    var columns = lines.First().Split('\t'); 
    foreach (var columnName in columns) 
     this.dataGridView.Columns.Add(columnName, columnName); 

    foreach (var line in lines.Skip(1)) 
    { 
     var cells = line.Split('\t'); 
     // This operation is too slow when applied to a huge amount of rows: 
     this.dataGridView.Rows.Add(cells);     
    }    
} 

我的問題是Rows.Add(cells)太慢(我有一個巨大的數據量)。

這是stringTable內容的例子:

TIME Temperature 
30.03.1992 10:00:00 7.500 
30.03.1992 11:00:00 9.300 
30.03.1992 12:00:00 10.000 
30.03.1992 13:00:00 10.400 
30.03.1992 14:00:00 11.400 
30.03.1992 15:00:00 11.800 
... 

我想用一個BindingList並將其設置爲DataSource,這將使它更快。問題是我不知道先驗的列數(在本例中只是「TIME,Temperature」,但可能是「TIME,Temperature,Rainfall,...,Other」)。

+0

是否提前知道最大列數組?如果是這樣,有一個靜態數據網格與所有這些列,並根據您綁定的特定數據隱藏列。然後,您可以創建一個數據源,其中包含所有列,但只有填充了數據的相關列。 – user469104

回答

2

不要將行逐行添加到網格中。首先創建循環中的所有行,然後將其全部添加到網格中,並使用AddRange的單個調用。

或者,填寫DataTable或其他合適的列表,然後將其綁定到網格。

如果你有太多的數據,這仍然太慢,那麼你可能需要看看虛擬化網格。

+0

關於在循環中創建行,我嘗試了這種方法,但是我發現沒有可能(?)獨立創建行。看到這些答案:http://stackoverflow.com/a/10063825/831138 <=所有這些方法來創建新的DataRows是複雜的,似乎取決於DataGridView本身。 –

+0

等待,它看起來像第二個建議(「或者填充一個DataTable或其他合適的列表,然後將其綁定到網格上。」)就足夠了!謝謝!如果其他人正在尋找同樣的東西:1)'var dataTable = new DataTable();',2)向dataTable添加列,3)'dataTable.Rows.Add(cells);'和4)'this。 dataGridView.DataSource = dataTable;'。 –

+0

使用AddRange肯定也會起作用。 – TaW

0

如果你不想改變你的代碼嘗試:

  • 暫停DataGridView拉絲過程中FillDataGridView
  • 恢復DataGridView在過程

暫停控制圖紙你的畫到底可以使用此代碼:

SendMessage(ctrlControl.Handle, WM_SETREDRAW, 0, 0) 

要繼續控制圖紙您可以使用此代碼:

SendMessage(ctrlControl.Handle, WM_SETREDRAW, 1, 0) 
ctrlControl.Refresh() 

還記得爲了防止萬一的問題使用Try/Catch/Finally塊不順心和DataGridView繪製將暫停。

Try 
    Application.DoEvents() 

    Me.Cursor = Cursors.WaitCursor 

    SuspendControlDrawing(yourDataGridView) 

    FillDataGridView(stringTable) 

Catch ex As Exception 
    MsgBox(ex.Message) 

Finally 

    Try 
     ResumeControlDrawing(yourDataGridView) 
    Catch ex As Exception 
    End Try 

    Me.Cursor = Cursors.Default 

End Try 
+0

與簡單使用SuspendLayout和ResumeLayout相比,有什麼區別/優勢嗎? – TaW

+0

如果我記得SuspendLayout和ResumeLayout有閃爍的問題。 – tezzo