为什么 DataTable.Rows.ImportRow 在传递新创建的 DataRow 时不起作用? [英] Why DataTable.Rows.ImportRow doesn't work when passing new created DataRow?

查看:26
本文介绍了为什么 DataTable.Rows.ImportRow 在传递新创建的 DataRow 时不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to add newRow to MyHandler and it should add that row to the table that was built internally from the "scheme" that was passed to the MyHandler. The problem is when I use dt.ImportRow(row); it doesn't add any row. If I add newRow to t table and then do handler.Add(t.row[t.Rows.Count - 1]); so it works, but I don't want to add to t table. The t is just so I could create new row.

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

Why dt.ImportRow(row); doesn't work? How to fix it?

{
   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);
    }
}

推荐答案

您应该只使用 ImportRow 从另一个 DataTable 添加行.根据 MSDN,使用 创建的行DataTable.NewRow 应与 DataTable.Rows.Add 一起添加.

You should only use ImportRow to add rows from another DataTable. Per MSDN, rows created with DataTable.NewRow should be added with DataTable.Rows.Add.

这篇关于为什么 DataTable.Rows.ImportRow 在传递新创建的 DataRow 时不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆