【问题标题】:Copying a subset of columns from one datagridview to a new datagridview in c#在c#中将列的子集从一个datagridview复制到一个新的datagridview
【发布时间】:2012-08-03 14:46:16
【问题描述】:

比方说,我们在一个 datagridview 中有 10 列。我在这 10 列中有 20 行数据。

动态地,我正在隐藏(将列的 .Visible 属性设置为 false)几列 - 例如第 1、2、4、5 列。

现在我想将可见列的内容(20 行数据,6 个可见列 - 3、6、7、8、9、10)复制到新的 datagridview。

有什么建议/建议/链接吗?

我研究了这个论坛,但找不到讨论将列的子集从一个 datagridview 复制到另一个的帖子。

谢谢。

【问题讨论】:

    标签: c# datagridview copy


    【解决方案1】:

    试试这个(你没有指出它是 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++;
    }
    

    我承认这是丑陋且相当蛮力的,但我对其进行了测试并且它有效。可能有更好的方法可以做到这一点,但我希望这至少应该对你有所帮助。

    【讨论】:

    • 嗨蒂姆,感谢您的代码。它运行良好,符合预期。
    【解决方案2】:

    现在无法测试..

    foreach (DataGridViewColumn dgvCol in dgv1.Columns)
    {
       if (dvgCol.visible) dgv2.Columns.Add((DataGridViewColumn) dgvCol.Clone());
    }
    

    【讨论】:

      猜你喜欢
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多