ADO.NET delete and addnew problem ?

J

jiatiejun

my program want to modify a table with DataGrid control,

the database is access2000 mdb format,

after remove a row from DataSet (ex:
myDataSet.myTable.Rows.RemoveAt(myIndex))

I add a new row to DataSet (ex: MyDataSet.myTable.Rows.Add(myDataRow))

when deleted row 's PK equ addnew row's PK

the DataSet can't to Update

why ?

I want allow user delete a row, and can add a new row with same PK column
value,
How do it ?

thanks
 
W

William Ryan

When you say it can't update...are you throwing an exception, or is it
going through and just not submitting the changes?
 
G

Greg

Are you calling AcceptChanges on DataSet after your update? If not, the
DataSet will reflect the original DataRow values.
 
N

Neil McKechnie

What you are doing is completely removing the row from the datatable. Once
this is done, Update will not be able to find the datarow at all, and so it
will not be deleted from the database. When you add the new row, it will of
course encounter a primary key constraint error.

The datarow's Delete method is what you should be using. This marks the row
as deleted, but does not remove it from the collection. Hence, Update is
able to then reflect the deletion into the underlying data source.

Bear in mind that the order in which the dataadaptor finds the rows can be
significant. If it were to find the inserted row before the deleted one you
would still get an error. To gain control over the order of operations, you
can use the dataset's GetChanges method to find the deletions and apply them
before the inserts.
Dim ds2 as DataSet
ds2 = ds1.GetChanges(DatRowState.Deleted)
adapter.Update(ds2)
ds2 = ds2.GetChanges(DataRowState.Added)
adapter.Update(ds2)

etc.

Hope this helps,

Neil.
 
G

Greg Robinson

Neil, I thought the same. Nowhere though does he state if he is calling
Delete or Remove. I assumed Delete, which as you state marks the
DataRow for deletion so that the delete is successful on the call to
Update on DataAdapter. Without knowing which method he is calling on
DataRow, I do not think we can assume this is his problem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top