问题
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