如何将数据添加到C#DataTable

时间:2013-11-05 16:00:57

标签: c# import datatable datarow

我认为这很容易但我在这里...我只是想在现有的DataTable中添加一个新行,但该表不会占用我的行......

Debug.Print("My Achv Count Before: {0}", Manager.achievementsMine.Rows.Count);
DataRow newRow = Manager.achievementsMine.NewRow();
newRow.SetField<int>("CT_Q", count);
newRow.SetField<DateTime>("CMPL_D", DateTime.Now);
newRow.SetField<string>("USER_LAN_I", Manager.userID);
newRow.SetField<string>("ACHV_I", ACHV_I);
Manager.achievementsMine.ImportRow(newRow);
Manager.achievementsMine.AcceptChanges();
Debug.Print("My Achv Count After: {0}", Manager.achievementsMine.Rows.Count);

'Debug.Print'之前/之后的两行都显示了44的计数。为什么'after'调试告诉我45因为我刚刚导入了一个新行并告诉了DataTable接受这些变化?

编辑: 我尝试重写一些newRow部分,但没有改变:

Debug.Print("My Achv Count Before: {0}", Manager.achievementsMine.Rows.Count);
DataRow newRow = Manager.achievementsMine.NewRow();
newRow["CT_Q"] = count;
newRow["CMPL_D"] = DateTime.Now;
newRow["USER_LAN_I"] = Manager.userID;
newRow["ACHV_I"] = ACHV_I;
Manager.achievementsMine.ImportRow(newRow);
Manager.achievementsMine.AcceptChanges();
Debug.Print("My Achv Count After: {0}", Manager.achievementsMine.Rows.Count);

1 个答案:

答案 0 :(得分:6)

如果您想使用NewRow,则必须Add稍后DataRow到表:

DataRow newRow = Manager.achievementsMine.NewRow();
newRow.SetField<int>("CT_Q", count);
newRow.SetField<DateTime>("CMPL_D", DateTime.Now);
newRow.SetField<string>("USER_LAN_I", Manager.userID);
newRow.SetField<string>("ACHV_I", ACHV_I);
Manager.achievementsMine.Rows.Add(newRow);

另一种方法是使用DataRowColection.Add

DataRow newRow = Manager.achievementsMine.Rows.Add();
// you don't need to add this row since it's already added.

注意:如果要稍后将新行插入数据库,请不要调用AcceptChangesAcceptChanges会将RowState更改为未更改,因此DataAdapter无法检测到此行是新行。 DataAdapter本身会在Update结束时调用它。