Problem : VB.NET DataGridView Paste to multiple cells

Problem : VB.NET DataGridView Paste to multiple cells

I have a DGV in a VB.NET project (VS 2008).

There is one column where I need the user to be able to copy a value from one row, and paste into multiple cells, like one would in Excel.

The user will select and copy the required cell to clipboard, then select multiple rows, then paste.  I need code to pick up the paste event, and then identify the selected rows, and paste the clipboard value to each row.

Solution : VB.NET DataGridView Paste to multiple cells

Actually it works exactly like you’ve described….

Below is an example, where you’ve got a ContextMenuStrip with a “Copy” and “Paste” item (to provide the “right click” context menu)

Dim CopyColumnIndex As Integer

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
‘TODO: This line of code loads data into the ‘NorthWindDataSet.Products’ table. You can move, or remove it, as needed.
Me.ProductsTableAdapter.Fill(Me.NorthWindDataSet.Products)

‘ build a context menu for a copy/paste
End Sub

Private Sub CopyToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CopyToolStripMenuItem.Click
‘ get the selected cell
If DataGridView1.SelectedCells.Count > 0 Then
‘ remember which column this came from
CopyColumnIndex = DataGridView1.SelectedCells(0).ColumnIndex
‘ copy the text to the clipboard
My.Computer.Clipboard.SetText(DataGridView1.SelectedCells(0).Value.ToString)
End If

End Sub

Private Sub PasteToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles PasteToolStripMenuItem.Click

If My.Computer.Clipboard.ContainsText Then
‘ loop thru each selected row and replace the value for that column
For Each dgr As DataGridViewRow In DataGridView1.SelectedRows
dgr.Cells(CopyColumnIndex).Value = My.Computer.Clipboard.GetText
Next
End If
End Sub