1

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

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!! 'Rows.Add' worked! I can't believe I didn't think of that because I've been doing the exact same thing for dynamically created HTML tables in C# code-behind for years now: Table.Rows.Add(TableRow)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.