简体   繁体   English

当我删除索引0时,C#DataRow.Delete()正在清除DataTable

[英]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. 当我删除索引0时,C#DataRow.Delete()正在清除DataTable。当我删除索引为1或更大的行时,它可以正常工作。 The DataTable reportDetails has 215 rows. 数据表reportDetails具有215行。 The first row, index 0, has all nulls. 第一行,索引为0,全为空。 When i = 1 the row at index 1 is deleted and I end up with 214 rows. 当i = 1时,索引1的行将被删除,最后我得到214行。 When i = 0 all rows are deleted. 当i = 0时,将删除所有行。

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) 编辑:当我做.RemoveAt(0)时,会发生相同的事情

The DataTable had Constraints that caused all rows to delete when a specific row was deleted. DataTable具有一些约束,这些约束会导致在删除特定行时删除所有行。 In this case the row at index 0. I added this code and now .Delete() works correctly: 在这种情况下,索引为0的行。我添加了此代码,现在.Delete()可以正常工作:

// 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. 但是,将DataTable复制到没有限制的新DT中然后删除该行的代码较少。 It's also more clear because nobody will have to wonder about DataSet relations or foreign key constraints. 这也更加清楚了,因为没有人会怀疑DataSet关系或外键约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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