如何构建一个DataGridView的DataTable? [英] How to build a DataTable from a DataGridView?
问题描述
我可以很好地向后看着这个问题,但我很好奇,没有少。有没有办法建立一个数据表
从什么是在的DataGridView
当前显示的?
需要明确的是,我知道你可以做到这一点数据表数据=(数据表)(dgvMyMembers.DataSource);
然而,包括隐藏的列。我想从仅显示的列构建。
希望是有道理的。
所以,我最后想的一对夫妇的答案,因为这似乎是最佳的组合。下面是我在努力。基本上,我创建从数据源的数据表,然后向后工作的基础上,如果一列是否可见。但是,它会删除一个专栏中,我得到了集合被修改后,枚举操作可能不会对
。 的foreach
的下一次执行
我很困惑,我不的的尝试的修改的DataGridView
,只有数据表
所以这是怎么回事?
数据表数据= GetDataTableFromDGV(dgvMyMembers);
私人数据表GetDataTableFromDGV(DataGridView中DGV)
{
VAR DT =((数据表)dgv.DataSource).Copy();
的foreach(在dgv.Columns的DataGridViewColumn列)
{
如果(!column.Visible)
{
dt.Columns.Remove(column.Name);
}
}
返回DT;
}
好了,你可以做
数据表数据=(数据表)(dgvMyMembers.DataSource);
然后用
data.Columns.Remove(...);
我认为这是最快的方法。这将修改数据源表,如果你不想要的话,那么表中的副本是reqired。另外要注意, DataGridView.DataSource
是不一定数据表
键入
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
?
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.
Hope that makes sense.
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
.
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;
}
Well, you can do
DataTable data = (DataTable)(dgvMyMembers.DataSource);
and then use
data.Columns.Remove(...);
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屋!