簡體   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