簡體   English   中英

C# 使用列表填充 DataGrid <list<string> &gt;? </list<string>

[英]C# populate DataGrid with List<List<string>>?

假設我在 WinForms (C#) 中有一個 DataGrid。

我想填充它,但我的數據是這種格式:

List<List<string>> datas;

對於簡單的測試,我添加了值:

List<List<string>> ds = new List<List<string>>();
List<string> row1 = new List<string>();
row1.Add("col1");
row1.Add("col2");
row1.Add("col3");
ds.Add(row1);

當我將ds添加為網格的數據源時,它會顯示我不理解的內容:

grid.DataSource = ds;

在此處輸入圖像描述

我也試過 LINQ,但沒有成功,datagrid 是空的。 我該如何解決這個問題?

如果這比手動迭代和填充 for 循環更快,我會在有或沒有 LINQ 的情況下這樣做。

我修改了此處找到的代碼以滿足您的需求;

private void Form1_Load(object sender, EventArgs e)
{

  List<List<string>> list = new List<List<string>>();
  list.Add(new List<string>()
  {
    "Row 1, Col 1",
    "Row 1, Col 2",
    "Row 1, Col 3",
  });
  list.Add(new List<string>()
  {
    "Row 2, Col 1",
    "Row 2, Col 2",
    "Row 2, Col 3",
  });
  list.Add(new List<string>()
  {
    "Row 3, Col 1",
    "Row 3, Col 2",
    "Row 3, Col 3",
  });

  DataTable table = ConvertListToDataTable(list);
  dataGridView1.DataSource = table;
}

static DataTable ConvertListToDataTable(List<List<string>> list)
{

  DataTable table = new DataTable();

  int columns = 0;
  foreach (var item in list)
  {
    if (item.Count > columns)
    {
      columns = item.Count;
    }
  }

  for (int i = 0; i < columns; i++)
  {
    table.Columns.Add();
  }

  foreach (var item in list)
  {
    DataRow new_row = table.NewRow();
    foreach(var col in item)
    {
      new_row[item.IndexOf(col)] = col;
    }
    table.Rows.Add(new_row);
  }

  return table;
}

它按以下方式返回數據網格

在此處輸入圖像描述

暫無
暫無

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

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