Chrisetiquette
Chrisetiquette

Reputation: 321

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

Upvotes: 2

Views: 2095

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125312

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.

Upvotes: 1

Related Questions