为什么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一起添加。