C# 在c中将列的子集从一个datagridview复制到一个新的datagridview#
比方说,我们在一个datagridview中有10列。我在这10列中有20行数据 动态地,我隐藏(将列的.Visible属性设置为false)一些列,比如列1、2、4、5 现在我想将可见列的内容(20行数据,6个可见列-3、6、7、8、9、10)复制到新的datagridview 有什么建议/建议/链接吗 我研究过这个论坛,没有找到一篇讨论将列子集从一个datagridview复制到另一个datagridview的帖子 谢谢 现在无法测试它C# 在c中将列的子集从一个datagridview复制到一个新的datagridview#,c#,datagridview,copy,C#,Datagridview,Copy,比方说,我们在一个datagridview中有10列。我在这10列中有20行数据 动态地,我隐藏(将列的.Visible属性设置为false)一些列,比如列1、2、4、5 现在我想将可见列的内容(20行数据,6个可见列-3、6、7、8、9、10)复制到新的datagridview 有什么建议/建议/链接吗 我研究过这个论坛,没有找到一篇讨论将列子集从一个datagridview复制到另一个datagridview的帖子 谢谢 现在无法测试它 foreach (DataGridViewColumn
foreach (DataGridViewColumn dgvCol in dgv1.Columns)
{
if (dvgCol.visible) dgv2.Columns.Add((DataGridViewColumn) dgvCol.Clone());
}
试试这个(您没有指出它是否是ASP.NET、WinForms等-此示例基于WinForms)。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++;
}
//设置一个列表以保存可见列的索引
List visibleColumns=新列表();
foreach(dgv1.Columns中的DataGridViewColumn列)
{
如果(列可见)
{
dgv2.Columns.Add((DataGridViewColumn)col.Clone());
visibleColumns.Add(列索引);
}
}
//现在添加列中的数据
//为第二个DataGridView的当前行索引设置计数器
int rowIndex=0;
foreach(dgv1.Rows中的DataGridViewRow行)
{
//向DataGridView添加新行
dgv2.Rows.Add();
//循环浏览可见列
for(int i=0;i
我承认这是一种丑陋而残忍的暴力,但我测试了它,它成功了。也许有更好的方法可以做到这一点,但我希望这至少会对您有所帮助。嗨,蒂姆,谢谢您的代码。它工作得很好,正如预期的那样。