2014-02-13 30 views
0

如何創建具有可變列數的DataGrid表?如何爲DataGrid表創建可變數量的列?

例如:假設我們有一個整數列表列表List<List<int>>。所有內部列表具有相同的長度n。現在我想爲每個整數列表創建一行,併爲每個整數添加一個額外的列。

例如:對於兩個整數列出{1, 2, 3}4, 5, 6的DataGad是這樣的:

1 | 2 | 3 
--+---+--- 
4 | 5 | 6 

通常情況下,我創造了我的DataGrid行元素的自己的類,像

class MyDataGridRecord { 
    public int first { get; set; } 
    public int second { get; set; } 
    ... 
} 

但是因爲我不知道我有多少列,所以我不能用固定數量的字段來編寫這樣一個類。

+0

所以你說,你有3列在這個例子中,而不是在正確的每一個例子嗎?那列是如何變化的? – paqogomez

+0

的確,整數列表的長度可能會有所不同。另一個例子可以是:「{1,2,3,4}」和「{5,6,7,8}」。 –

回答

1

我想你可以做這樣的事情:

var list = new List<List<int>> 
     { 
      new List<int>() {2, 3, 4, 5}, 
      new List<int>() {2, 3, 4, 5}, 
      new List<int>() {2, 3, 4, 5}, 
      new List<int>() {2, 3, 4, 5} 
     }; 

var columnCount = list[0].Count; 

for (int i = 0; i < columnCount; i++) 
{ 
    dataGridView1.Columns.Add(i.ToString(),"Column " + i+1); 
} 
for (int k = 0; k < list.Count; k++) 
{ 
    dataGridView1.Rows.AddCopy(0); 
} 


for (int k = 0; k < list.Count; k++) 
{ 
     for (int i = 0; i < list[k].Count; i++) 
     { 
      dataGridView1.Rows[k].Cells[i].Value = list[k][i]; 
     } 
} 
相關問題