簡體   English   中英

如何為DataGrid表創建可變數量的列?

[英]How to create a variable number of columns for a DataGrid table?

如何創建具有可變列數的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; }
  ...
} 

但是由於我不知道我有多少列,所以無法編寫具有固定數量字段的類。

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

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];
      }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM