繁体   English   中英

在未绑定的 DataGridView 中复制和粘贴选定的行

[英]Copy and Paste Selected Rows in an unbound DataGridView

我尝试在 DataGridView 属性中将 ClipboardCopyMode 更改为“EnableWithoutHeaderText”,但这不起作用。 另外,我尝试使用下面的代码以编程方式执行此操作,但它也不起作用。 请帮忙。

 Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    Me.DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
End Sub

您可以使用单元格值克隆选定的行,然后您可以使用InsertRange插入副本单元格。 注意这种方式适用于未绑定的DataGridView ,如果您的DataGridView已绑定,那么您应该复制控件的DataSource的记录。

C#

var insertAt = 0;
var rows = dataGridView1.SelectedRows.Cast<DataGridViewRow>()
                        .OrderBy(r=>r.Index)
                        .Select(r=>{
                            var clone = r.Clone() as DataGridViewRow;
                            for (int i = 0; i < r.Cells.Count; i++)
                                clone.Cells[i].Value= r.Cells[i].Value;
                            return clone;
                        }).ToArray();
dataGridView1.Rows.InsertRange(insertAt, rows);

VB

Dim insertAt = 0
Dim rows = DataGridView1.SelectedRows.Cast(Of DataGridViewRow) _
                        .OrderBy(Function(r) r.Index) _
                        .Select(Function(r)
                                    Dim clone = DirectCast(r.Clone(), DataGridViewRow)
                                    For i = 0 To r.Cells.Count - 1
                                        clone.Cells(i).Value = r.Cells(i).Value
                                    Next
                                    Return clone
                                End Function) _
                        .ToArray()
DataGridView1.Rows.InsertRange(insertAt, rows)

笔记

  • DataGridView.Rows集合也有InsertCopies方法。 但是该方法只能复制连续范围的行。 虽然上面的代码也可以复制不连续的选择。
  • 我使用OrderBy(r=>r.Index)以您在网格中看到的相同顺序插入行,而不是选择它们的顺序。
  • DataGridViewRow.Clone方法克隆具有所有属性但不具有单元格值的行,因此我使用 for 循环复制值。
  • 您可以简单地基于上述代码创建一个扩展方法。 它会更可重用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM