为什么 DataTable.Rows.ImportRow 在传递新创建的 DataRow 时不起作用

本文关键字:创建 DataRow 不起作用 新创建 Rows DataTable ImportRow 为什么 | 更新日期: 2023-09-27 18:37:06

我需要将newRow添加到MyHandler,它应该将该行添加到从传递给MyHandler的"方案"内部构建的表中。问题是当我使用dt.ImportRow(row);时,它不会添加任何行。如果我将newRow添加到表中t然后执行handler.Add(t.row[t.Rows.Count - 1]);它就可以工作,但我不想添加到表中tt只是为了让我可以创建新行。

为什么dt.ImportRow(row);不起作用?如何解决?

{
   var t = new DataTable();
   t.Columns.Add(new DataColumn("Col1", typeof(string)));
   t.Columns.Add(new DataColumn("Col2", typeof(byte)));
   t.Columns.Add(new DataColumn("Col3", typeof(byte)));
   t.Rows.Add("a", 1, 1);
   t.Rows.Add("b", 2, 2);
   // MyHandler build internal table from the scheme
   var handler = new MyHandler(t.Clone());
   var newRow = t.NewRow();
   row["Col1"] = "c";
   row["Col2"] = 3;
   row["Col3"] = 3;
   handler.Add(row);
}
public class MyHandler
{
    DataTable dt;
    public class MyHandler(DataTable scheme)
    {
        dt = scheme;
    }
    public void Add(DataRow row)
    {
       dt.ImportRow(row);
    }
}

为什么 DataTable.Rows.ImportRow 在传递新创建的 DataRow 时不起作用

只应使用 ImportRow 从另一个数据表添加行。 根据 MSDN,使用 DataTable.NewRow 创建的行应添加 DataTable.Rows.Add