【问题标题】:Add entire row to DataTable at once using list使用列表一次将整行添加到 DataTable
【发布时间】:2012-07-04 12:02:07
【问题描述】:

我只想将 List 添加为 DataTable 整行。这是我尝试过的代码。

private static DataTable _table = new DataTable();

List<string> tempList = new List<string>();

// tempList = {"A1","A2","A3","A4","A5","A6"}

_table.Rows.Add(tempList);

预期输出:

      col1|col2 |col3 |col4  |col5| col6
      ----+-----+-----+------+----+--
row1   A1 |  A2 | A3  |  A4  | A5 |  A6

但是这对我不起作用。它将数据集合插入到第一列。

实际输出:

      col1      |col2 |col3 |col4  |col5| col6
      ----------+-----+-----+------+----+--
row1   A1,A2,A3.|     |     |      |    |  

请帮助我使用列表添加整行。谢谢

【问题讨论】:

  • 你在DataTable上定义了一些列吗?
  • 是的。但是 tempList.ToArray() 是解决方案。 :0
  • 理想情况下你需要同时做这两个,否则你会遇到问题:-)

标签: c# list datatable


【解决方案1】:

DataRowCollection.Add() 方法需要Object[],所以你应该尝试一下:

_table.Rows.Add(tempList.ToArray());

【讨论】:

    【解决方案2】:

    Rows.Add() 接受 parms[],您可以通过将 list 转换为数组来实现。

    _table.Rows.Add(tempList.ToArray());
    

    【讨论】:

      【解决方案3】:
       DataTable dt = new DataTable();
              dt.Columns.Add();
              dt.Columns.Add();
              dt.Columns.Add();
              List<string> tempList = new List<string>() { "a", "b", "c" };
              dt.Rows.Add(tempList.ToArray<string>());
      

      【讨论】:

        猜你喜欢
        • 2013-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-27
        • 2014-12-26
        • 1970-01-01
        • 1970-01-01
        • 2019-03-26
        相关资源
        最近更新 更多