DataTable.ImportRow不添加行

我正在尝试创建一个DataTable,然后添加几行。 这是我的代码:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; namespace thisNamespace { class Program { static void Main(string[] args) { DataTable dt=new DataTable(); dt.Columns.Add("XYZID"); DataRow dr=dt.NewRow(); dr["XYZID"]=123; dt.ImportRow(dr); dr["XYZID"] = 604303; dt.ImportRow(dr); } } } 

当我逐步完成程序时, dr已成功初始化并填充了值,但是在ImportRow(dr)dt的行数仍为0.我觉得我必须遗漏一些明显的东西。 这里出了什么问题?

试试这段代码:

dt.Rows.Add(dr)

如果该行是分离的(就像它在第一次创建时那样),则ImportRows将以静默方式失败(无exception) – 能够导入您必须将行添加到表中的行。 之后,您可以将其导入其他表。

它可以帮助你

 DataTable table = new DataTable(); table.Columns.Add("Dosage", typeof(int)); table.Columns.Add("Drug", typeof(string)); table.Columns.Add("Patient", typeof(string)); table.Columns.Add("Date", typeof(DateTime)); // // Here we add five DataRows. // table.Rows.Add(25, "Indocin", "David", DateTime.Now); table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now); table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now); table.Rows.Add(21, "Combivent", "Janet", DateTime.Now); table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now); 

您首先需要添加行:

  dt.Rows.Add(dr); 

然后你必须调用以下方法来提交它:

  dt.AcceptChanges();