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

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

问题描述

我需要删除的数据表(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与未更改或修改的不同。如果您删除()添加的行,它不只是从集合中删除它,因为数据存储presumably从来不知道也无妨。删除()在一个不变或修改的行只是标记为其他人指示为删除。

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天全站免登陆