Why DataTable.Rows.ImportRow doesn't work when

2019-01-20 15: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条回答
放我归山
2楼-- · 2019-01-20 16:10

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.

查看更多
登录 后发表回答