【问题标题】:C# - Jagged string[][] arrayname into DataTable/DataGridViewC# - 将锯齿形字符串 [] [] 数组名放入 DataTable/DataGridView
【发布时间】:2018-07-14 20:20:58
【问题描述】:

我是 C# 编程和使用交错数组操作主题的新手。

我的 string[][] 数组名中存储了一些数据,并希望在 datagridview 中显示它。

如果你能就这个案子给我建议,我将不胜感激。

【问题讨论】:

  • 您也是 StackOverflow 的新手,这与典型的互联网论坛不同。我建议您阅读How to Ask 并使用tour。并且可能会修复您的 Google - 这里已经有 250 篇关于该主题的帖子。

标签: c# string datagridview datatable jagged-arrays


【解决方案1】:

您需要创建数据集,通常我使用DataTable,我已经为您的问题起草了解决方案,但您必须使用Linq:

var ListName = arrayname.ToList();
//get number of column, probalby you dont need it
int cols = ListName.Select(r => r.Length).Max();

//Create a datasource
DataTable dt = new DataTable();

//Write column, probalby you dont need it
for (int f = 0; f < cols; f++)
    dt.Columns.Add("Col " + (f+1));

foreach (var row in ListName) {
    //make a row
    List<string> Lrow = new List<string>();
    Lrow.AddRange(row);
    //if row is too short add fields
    if (Lrow.Count < cols)
        for (int i = Lrow.Count; i < dt.Columns.Count; i++) {
            Lrow.Add("");
        }
    //at last add row to dataTable
    dt.Rows.Add(Lrow.ToArray());
}
//and set dataGridView's DataSource to DataTable
dataGridView1.DataSource = dt;

The result should be this

【讨论】:

  • 是否有可能使dataGridView中的列标题是第一行数组属性,知道它有点乱,因为第一行上的属性数可能比接下来的要少行。但是让我们假设每个属性的数量是相同的。所以列标题是a[0][],正文是a[1][]....?非常感谢:)
  • @YutuKAron 我创建的列数等于最长数组的长度 cols 是我的最大长度 Select(r =&gt; r.Length) 选择所有长度,我得到最大 .Max()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
  • 2021-12-14
  • 2014-10-16
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
相关资源
最近更新 更多