比方说,我们在一个 datagridview 中有 10 列。我在这10列中有20行数据。
动态地,我隐藏了几列(将列的 .Visible 属性设置为 false) - 例如第 1、2、4、5 列。
现在我想将可见列的内容(20 行数据,6 个可见列 - 3、6、7、8、9、10)复制到新的 datagridview。
有什么建议/建议/链接吗?
我研究过这个论坛,但找不到讨论如何将列子集从一个 datagridview 复制到另一个 datagridview 的帖子。
谢谢。
最佳答案
尝试一下(您没有指出它是否是 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++;
}
我承认这很丑陋而且相当暴力,但我测试了它并且它有效。可能有更好的方法来做到这一点,但我希望这至少应该对您有所帮助。
关于c# - 在 C# 中将列的子集从一个 datagridview 复制到新的 datagridview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7130140/