为什么DataTable.Rows.ImportRow在传递新创建的DataRow时不起作用?
我需要将newRow
添加到MyHandler
,它应该将该行添加到从传递给MyHandler的“scheme”内部构建的表中。 问题是当我使用dt.ImportRow(row);
它不会添加任何行。 如果我将newRow
添加到t
表然后执行handler.Add(t.row[t.Rows.Count - 1]);
所以它的工作原理,但我不想添加到t
表。 这是我可以创建新行。
为什么dt.ImportRow(row);
不起作用? 怎么解决?
{ 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.NewRow
一起添加。