GeniuS BraiN GeniuS BraiN - 1 year ago 70 Question

Delete rows from datatable properly in .Net

Basically, I have a MySQL DB I'm binding the data from one column of a table into a ListBox.. I want to allow users to add/edit/remove items and to be able to save/reject changes

For deletion, I want the user to be able to delete the selected item in the ListBox.. here's what I've tried so far



But this doesn't actually delete the row from the DataTable until updating it using
method, so the next index in the ListBox will refer to the deleted row in the DataTable.


This works fine, but when updating the DataTable (after the user clicks
), the deleted rows aren't even deleted.

(3) Tried calling


And I get the same result as the second one above.

Here's how I finally update the DataTable:

Dim cmdBldr As New MySqlCommandBuilder(da)

So, is there a way to allow users to add/delete any number of rows to the DataTable BEFORE updating it?

Answer Source

Bind the DataTable to a BindingSource (which you would add in the designer) and bind that to the ListBox. You would then delete the selected record by calling RemoveCurrent on the BindingSource. That will flag that row as Deleted and it will be excluded by the BindingSource.

DO NOT call AcceptChanges on anything. Doing so will indicate to the data adapter that there are no changes to save. Call Update on the data adapter to save the changes from the DataTable back to the database. That will call AcceptChanges internally after a successful save. When AcceptChanges is called, any rows marked Deleted are removed from the DataTable, while any rows marked Added or Modified are marked Unchanged.