c# - 在 C# 中将列的子集从一个 datagridview 复制到新的 datagridview

标签 c# datagridview copy

比方说,我们在一个 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/

相关文章:

Vim 复制行号?

c# - 如何绑定(bind)到 WPF 中动态创建的单选按钮?

c# - 有没有办法在用户单击另一行中的单元格时保持选中 DataGridView 行?

c++ - 将 vector<Derived*> 转换为 vector<Base*> 时如何避免复制

c# - DataGridView.CellValueChanged 未在绑定(bind)的 DataGridView 上触发

c# - 具有两个数据源的 Datagridview

linux - 在Linux中如何实现镜像复制?

c# - 在 LINQ to SQL 中命名 parent 和 child

c# - MVC3 传回带有列表的对象列表

c# - 如何为 Odata 创建按 Id 获取的查询表达式