如何从 DataGridView 构建 DataTable? [英] How to build a DataTable from a DataGridView?

查看:27
本文介绍了如何从 DataGridView 构建 DataTable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能会倒推这个问题,但我仍然很好奇.有没有办法从 DataGridView 中当前显示的内容构建 DataTable?

I may well be looking at this problem backwards but I am curious none the less. Is there a way to build a DataTable from what is currently displayed in the DataGridView?

明确地说,我知道你可以这样做 DataTable data = (DataTable)(dgvMyMembers.DataSource); 但是这包括隐藏的列.我只想从显示的列中构建它.

To be clear, I know you can do this DataTable data = (DataTable)(dgvMyMembers.DataSource); however that includes hidden columns. I would like to build it from the displayed columns only.

希望这是有道理的.

所以我最终尝试了几个答案的组合,因为这似乎是最好的.以下是我正在尝试的内容.基本上我是从数据源创建数据表,然后根据列是否可见向后工作.但是,在删除一列后,我得到一个 Collection 被修改;枚举操作可能不会在 foreach 的下一次迭代中执行.

So I ended up trying a combination of a couple of answers as that seemed best. Below is what I am trying. Basically I am creating the DataTable from the DataSource and then working backwards based on if a column is visible or not. However, after it removes a column I get a Collection was modified; enumeration operation may not execute on the next iteration of the foreach.

我很困惑,因为我没有尝试修改DataGridView,只有DataTable,这是怎么回事?

I am confused as I am not trying to modify the DataGridView, only the DataTable so what's up?

DataTable data = GetDataTableFromDGV(dgvMyMembers);


    private DataTable GetDataTableFromDGV(DataGridView dgv)
    {
        var dt = ((DataTable)dgv.DataSource).Copy();
        foreach (DataGridViewColumn column in dgv.Columns)
        {
            if (!column.Visible)
            {
                dt.Columns.Remove(column.Name);
            }
        }
        return dt;
    }

推荐答案

好吧,你可以做

DataTable data = (DataTable)(dgvMyMembers.DataSource);

然后使用

data.Columns.Remove(...);

我认为这是最快的方式.这将修改数据源表,如果您不想要它,则需要复制表.另请注意,DataGridView.DataSource 不一定是 DataTable 类型.

I think it's the fastest way. This will modify data source table, if you don't want it, then copy of table is reqired. Also be aware that DataGridView.DataSource is not necessarily of DataTable type.

这篇关于如何从 DataGridView 构建 DataTable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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