简体   繁体   中英

C# DataRow.Delete() is clearing the DataTable when I delete index 0

C# DataRow.Delete() is clearing the DataTable when I delete index 0. When I delete the row at index 1 or greater it works fine. The DataTable reportDetails has 215 rows. The first row, index 0, has all nulls. When i = 1 the row at index 1 is deleted and I end up with 214 rows. When i = 0 all rows are deleted.

Here's my code:

int i = 0;

DataRow dr = reportDetails.Rows[i];
dr.Delete();
reportDetails.AcceptChanges(); 

What am I missing? Edit: The same thing happens when I do .RemoveAt(0)

The DataTable had Constraints that caused all rows to delete when a specific row was deleted. In this case the row at index 0. I added this code and now .Delete() works correctly:

// Remove any foreign key constraints
for (int i = reportDataSet.Tables.Count - 1; i >= 0; i--)
{
    var table = reportDataSet.Tables[i];
    for (int constraint = table.Constraints.Count - 1; constraint >= 0; constraint--)
        if (table.Constraints.CanRemove(table.Constraints[constraint]))
            table.Constraints.Remove(table.Constraints[constraint]);
}

However, the code to copy the DataTable into a new DT without constraints and then remove the row is fewer lines of code. It's also more clear because nobody will have to wonder about DataSet relations or foreign key constraints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM