Link to home
Start Free TrialLog in
Avatar of Observer_123
Observer_123

asked on

Copy selected rows from unbound datagridview and reinsert them in the same datagridview - VB.Net (WinForms)

Hi!
I have one datagridview, which I fill with code cell by cell.
I want in runtime to create a copy of curently selected rows and reinsert this rows just before the current selection in the same datagridview with the same content.
In this datagridview have 2 columns which are dropdowns in 5 and 7 column.
What is the best way and some code for that?
Avatar of Jorge Paulino
Jorge Paulino
Flag of Portugal image

Hi,
You can do something like this (you may need to change something).
I have used the keydown event for CTRL+V combination

    Private Sub DataGridView1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
        If e.Control AndAlso e.KeyCode = Keys.V Then
 
            Try
                For Each line As String In Clipboard.GetText.Split(vbNewLine)
                    Dim item() As String = line.Trim.Split(vbTab)
 
                    If item.Length = Me.DataGridView1.ColumnCount Then
                        Me.DataGridView1.Rows.Add(New Object() {item(0), item(1), item(2), item(3), item(4)})
                    End If
                Next
 
            Catch ex As Exception
                MessageBox.Show(ex.Message, My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
 
        End If
    End Sub

Open in new window

Opps, this is for 4 columns ... just change it to the required ones.
Avatar of Observer_123
Observer_123

ASKER

Hi!
The copy from clipboard is interesting, but it could be enought just duplication - we have selected rows , click a button and they are inserted. Is there some issue with dropdown copumns, or copy them as regular cells?
ASKER CERTIFIED SOLUTION
Avatar of Jorge Paulino
Jorge Paulino
Flag of Portugal image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
the last one looks mostly what I need, but in this case may it will be added at the end of datagridview.
any idea how to insert them just below the last selected row?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanxs:)