English 中文(简体)
在DataTable中添加/删除DataRow的正确方法是什么
原标题:What is the correct way to add/delete a DataRow to/from DataTable

我在为DataAdapter.Update()添加和删除DataTable中的DataRows时遇到了问题。我一直收到并发错误,但我不知道哪里出了问题。

当我在DataTable中添加和删除行时,就会发生这种情况。

目前,我添加的行如下:

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

并且我这样删除数据表中的最后一个逻辑行:

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

在进行了几次添加和删除之后,Update将失败,并出现并发异常。添加行的更好方法是什么?有人能帮忙发现错误吗?谢谢

最佳回答

将数据写入数据库(插入或更新),然后将数据从数据库读回数据表更容易。

问题回答

对于每次添加和删除u,请使用table.acceptchanges(),希望它能正常工作





相关问题
Remove all columns with no data from DataTable

If all the items for a particular column are empty, I want to remove that column from the DataTable. What s the most elegant way to do this operation on all columns in the DataTable?

Handle DataTable.DataRow cell change event

I have a DataTable that has several DataColumns and DataRow. Now i would like to handle an event when cell of this DataRow is changed. How to do this in c#?

Customize DataColumn.Expression handling in C#

I would like to change behavior of DataColumn.Expression so that when I write: DataColumn.Expression = "MyMethod(Price)" It will call MyMethod, pass value from Price column into it and display ...

热门标签