【问题标题】:Data table add column by column instead of row by row数据表逐列而不是逐行添加
【发布时间】:2014-09-23 17:38:02
【问题描述】:
col1    col2    col3
-----   -----   ----
1         4      7
2         5      8
3         6      9

有没有办法通过以下方式构建数据表:

  1. 将第 1 列添加为“col1”
  2. 为第 1 列添加值为 1,2,3 的行
  3. 重复下一列及其相应的行

我试图从以下代码开始,但卡在第二列及其行

dt.Columns.Add("col1")
dt.Rows.Add(1)
dt.Rows.Add(2)
dt.Rows.Add(3)

【问题讨论】:

  • 请说明您正在努力做得更好。之前的数据是什么样子的,所以我们可以告诉你想去哪里。

标签: .net vb.net datatable


【解决方案1】:

在表格中添加列和行后,您可以按列索引(可以是数字或列名)访问每行中的单元格:

    dt.Columns.Add("col1")
    dt.Columns.Add("col2")
    dt.Columns.Add("col3")

    dt.Rows.Add(dt.NewRow())
    dt.Rows.Add(dt.NewRow())
    dt.Rows.Add(dt.NewRow())

    'Populate column 1 using index 0
    dt.Rows(0)(0) = 1
    dt.Rows(1)(0) = 2
    dt.Rows(2)(0) = 3

    'Populate column 2 using index 1
    dt.Rows(0)(1) = 4
    dt.Rows(1)(1) = 5
    dt.Rows(2)(1) = 6

    'Populate column 3 using column name as cell index for a change
    dt.Rows(0)("col3") = 7
    dt.Rows(1)("col3") = 8
    dt.Rows(2)("col3") = 9

    'Add and populate another column later
    dt.Columns.Add("col4")
    dt.Rows(0)("col4") = 97
    dt.Rows(1)("col4") = 98
    dt.Rows(2)("col4") = 99

    'Add and populate another row later
    dt.Rows.Add(dt.NewRow())
    dt.Rows(3)("col1") = 10
    dt.Rows(3)("col2") = 20
    dt.Rows(3)("col3") = 30
    dt.Rows(3)("col4") = 40

【讨论】:

    猜你喜欢
    • 2018-12-07
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 2013-12-17
    • 2013-01-26
    • 1970-01-01
    相关资源
    最近更新 更多