Why DataTable.Rows.ImportRow doesn't work when passing new created DataRow?

依然范特西╮ 提交于 2019-11-30 06:04:22

问题


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.

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

回答1:


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.



来源:https://stackoverflow.com/questions/11035479/why-datatable-rows-importrow-doesnt-work-when-passing-new-created-datarow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!