删除数据表中的所有行 [英] Delete all rows in a datatable

查看:22
本文介绍了删除数据表中的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要删除数据表 (ADO.net) 中的所有行.我不想在这里使用 Foreach.

I need to delete all the rows in a datatable (ADO.net). I dont want to use Foreach here.

如何一次性删除所有行.

In one single how can I delete all the rows.

然后我需要更新数据表到数据库.

Then I need to update the datatable to database.

注意:我已经尝试过 dataset.tables[0].rows.clear 和 dataset.clear 但两者都不起作用

Note: I have tried dataset.tables[0].rows.clear and dataset.clear but both are not working

我也不想使用sql删除查询.

Also I dont want to use sql delete query.

如果您能提供答案,请发布除此之外的其他内容.

Post other than this if you able to provide answer.

推荐答案

'foreach' 也不是这个问题的简单答案——你会遇到枚举数对于更改的集合不再有效的问题.

'foreach' isn't such a simple answer to this question either -- you run into the problem where the enumerator is no longer valid for a changed collection.

这里的麻烦在于,DataRowState.Added 与 Unchanged 或 Modified 中的行的 Delete() 行为是不同的.如果您删除()添加的行,它只是将其从集合中删除,因为数据存储可能永远不知道它.未更改或修改的行上的 Delete() 只是将其标记为已删除,正如其他人所指出的那样.

The hassle here is that the Delete() behavior is different for a row in DataRowState.Added vs. Unchanged or Modified. If you Delete() an added row, it does just remove it from the collection since the data store presumably never knew about it anyway. Delete() on an unchanged or modified row simply marks it as deleted as others have indicated.

所以我最终实现了一个这样的扩展方法来处理删除所有行.如果有人有更好的解决方案,那就太好了.

So I've ended up implementing an extension method like this to handle deleting all rows. If anyone has any better solutions, that would be great.

    public static void DeleteAllRows(this DataTable table)
    {
        int idx = 0;
        while (idx < table.Rows.Count)
        {
            int curCount = table.Rows.Count;
            table.Rows[idx].Delete();
            if (curCount == table.Rows.Count) idx++;
        }
    }

这篇关于删除数据表中的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆