Domanda

I thought this would be fairly easy yet here I am... I am trying to simply add a new row to an existing DataTable but the table won't take my row...

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);

Both of the before/after 'Debug.Print' lines are showing me a count of 44. Why wouldn't the 'after' debug tell me 45 since I just imported a new row and told the DataTable to accept the changes?

EDIT: I tried rewriting some of the newRow parts but no change:

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);
È stato utile?

Soluzione

If you want to use NewRow you have to Add the DataRow later to the table:

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);

Another approach is using DataRowColection.Add:

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

Note: Don't call AcceptChanges if you want to insert the new row to the database later. AcceptChanges will change it's RowState to unchanged, hence a DataAdapter cannot detect that this row is new. The DataAdapter itself will call it at the end of Update.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top