[英]Copying a subset of columns from one datagridview to a new datagridview in c#
Lets say, we have 10 columns in one datagridview. 可以说,一个datagridview中有10列。 I have 20 rows of data in these 10 columns.
我在这10列中有20行数据。
Dynamically, I'm hiding (setting the .Visible property of the column to false) a few columns - say column 1, 2, 4, 5. 动态地,我隐藏了一些列(将列的.Visible属性设置为false)(例如第1、2、4、5列)。
Now I want to copy the contents of the columns which are visible (20 rows of data, 6 visible columns - 3, 6, 7, 8, 9, 10) to a new datagridview. 现在,我想将可见列的内容(20行数据,6可见列-3、6、7、8、9、10)复制到新的datagridview中。
Any suggestions / advise / links? 有什么建议/建议/链接吗?
I've researched this forum and could not find a post discussing about copying a subset of columns from one datagridview to another. 我已经研究了这个论坛,但是找不到有关讨论如何将一部分列从一个datagridview复制到另一个的文章。
thanks. 谢谢。
Try this (you didn't indicate whether it was ASP.NET, WinForms, etc - this example is based on WinForms). 试试这个(您没有指出它是否是ASP.NET,WinForms等-此示例基于WinForms)。 Christian's suggestion above is in the right direction, but when I tried it out
Clone()
didn't copy the values, and I couldn't see a way to get it to do that. 克里斯蒂安(Christian)的上述建议是朝正确的方向发展的,但是当我尝试使用
Clone()
时,它并没有复制值,而且我看不出有办法实现这一目标。
// Set up a List<T> to hold the indexes of the visible columns
List<int> visibleColumns = new List<int>();
foreach (DataGridViewColumn col in dgv1.Columns)
{
if (col.Visible)
{
dgv2.Columns.Add((DataGridViewColumn)col.Clone());
visibleColumns.Add(col.Index);
}
}
// Now add the data from the columns
// Set a counter for the current row index for the second DataGridView
int rowIndex = 0;
foreach (DataGridViewRow row in dgv1.Rows)
{
// Add a new row to the DataGridView
dgv2.Rows.Add();
// Loop through the visible columns
for (int i = 0; i < visibleColumns.Count; i++)
{
// Use the index of the for loop for the column in the target data grid
// Use the index value from the List<T> for the cell of the source target data grid
dgv2.Rows[rowIndex].Cells[i].Value = row.Cells[visibleColumns[i]].Value;
}
// Increment the rowIndex
rowIndex++;
}
I'll admit this is ugly and rather brute force, but I tested it and it worked. 我承认这是丑陋且相当残酷的力量,但我对其进行了测试并奏效。 There may be better ways to do it, but this should at least help you some, I hope.
也许有更好的方法可以这样做,但是我希望这至少应该对您有所帮助。
can't test it now.. 现在无法测试。
foreach (DataGridViewColumn dgvCol in dgv1.Columns)
{
if (dvgCol.visible) dgv2.Columns.Add((DataGridViewColumn) dgvCol.Clone());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.