开发者

What is the correct way to add/delete a DataRow to/from DataTable

开发者 https://www.devze.com 2023-02-10 20:50 出处:网络
I am facing problem adding and deleting DataRows from a DataTable that is meant for DataAdapter.Update(). I keep getting Concurrency error but I cannot figure where is wrong.

I am facing problem adding and deleting DataRows from a DataTable that is meant for DataAdapter.Update(). I keep getting Concurrency error but I cannot figure where is wrong.

It happens when i add and delete rows from a DataTable.

At the moment, I add rows like this:

table.Rows.Add(new string{null /*pk*/, "composite_FK1", "composite_FK2", "composite_FK3"});

and i delete the last logical row in the DataTable like this:

DataRow[] rows = table.Select(string.Empty, string.Empty, DataViewRowState.CurrentRows);

if (rows.Length > 0)
{
    DataRow row = rows[rows.Length 开发者_运维问答- 1];
    if (row.RowState == DataRowState.Added)
    {
        // directly remove this row because it is not in the database yet
        table.Rows.Remove(row);
    }
    else
    {
        // mark this row for deletion from the database
        row.Delete();
    }
}

After a few add and deletes, Update fails with Concurrency Exception. What can be a better way to add rows? Anyone can help spot the error please? Thanks.


It is easier to write your data to the database (inserts or updates), then read the data back from the database into your data table.


For every adding and deleting u use table.acceptchanges(), hope it will work fine

0

精彩评论

暂无评论...
验证码 换一张
取 消