简体   繁体   中英

Copy and Paste Selected Rows in an unbound DataGridView

I've tried changing the ClipboardCopyMode to "EnableWithoutHeaderText" in the DataGridView properties but this did not work. Also, I tried doing this programmatically with the code below, but it did not work either. Please help.

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

You can clone selected rows with values of cells, then you can use InsertRange to insert copies cells. Pay attention this way will work for an unbound DataGridView and if your DataGridView is bound, then you should copy records of the DataSource of control.

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)

Note

  • DataGridView.Rows collection also have InsertCopies method. But the method can only copy a contiguous range of rows. While above code can copy a non-contiguous selection as well.
  • I used OrderBy(r=>r.Index) to insert rows in the same order which you see in grid not with order of selecting them.
  • DataGridViewRow.Clone method clones a row with all its properties but not with cell values, so I copied values using the for loop.
  • You can simply create an extension method based on above code. It would be more reusable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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