theateist
theateist

Reputation: 14399

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

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

Upvotes: 2

Views: 6913

Answers (1)

cadrell0
cadrell0

Reputation: 17307

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.

Upvotes: 4

Related Questions