Add ContextMenu for each datagridview cell at run time in vb.net

In this article i will explain you how we can create dynamic context menu with cut,copy and paste menu items and how to add the this context menu to every cell of the datagridview at run time.Suppose if we have a DataGridView control that display some data and we want to add cut, copy and paste operations to each cell of the datagridview means if user want to cut the specified text of the cell than he can use right click with copy action.
 
The following example requires a datagridview control named DataGridView1.
Set the selectionMode property to CellSelect and MultiSelect to false.  
The following code binds the FDatagridview with the records:
 

     Private Sub Button1_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) Handles Button1.Click
 
        Dim constr As String = "put your connection string"
        Dim ds As New DataSet
        Dim con As New SqlClient.SqlConnection(constr)
        con.Open()
        Dim sqladap As New SqlClient.SqlDataAdapter("select * from tbl_Employee", con)
        sqladap.Fill(ds)
        DataGridView1.DataSource = ds.Tables(0)
 
        Dim _contextmenu As New ContextMenuStrip
        _contextmenu.Items.Add("Cut")
        _contextmenu.Items.Add("Copy")
        _contextmenu.Items.Add("Paste")
        AddHandler _contextmenu.ItemClicked, AddressOf contextmenu_click
        For Each rw As DataGridViewRow In DataGridView1.Rows
            For Each c As DataGridViewCell In rw.Cells
                c.ContextMenuStrip = _contextmenu
            Next
        Next
End Sub

 
From the below code- each time when user right click on the cell, cell will be focused and selected.
 

 
Private Sub DataGridView1_CellMouseDown(ByVal sender As System.Object, _
                     ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) _
                     Handles DataGridView1.CellMouseDown
        If e.RowIndex <> -1 And e.ColumnIndex <> -1 Then
            If e.Button = MouseButtons.Right Then
                Dim clickCell As DataGridViewCell = sender.Rows(e.RowIndex).Cells(e.ColumnIndex)
                clickCell.Selected = True
            End If
        End If
    End Sub

 
and below is the procedure of the dynamic contextMenuStrip’s click event, where we are performing cut, copy and paste operation:
 

    Private Sub contextmenu_click(ByVal sender As System.Object, _
                                  ByVal e As ToolStripItemClickedEventArgs)
        Dim clickCell As DataGridViewCell = DataGridView1.SelectedCells(0)
        Select Case e.ClickedItem.Text
            Case "Cut"
                Clipboard.SetText(clickCell.Value)
                clickCell.Value = ""
            Case "Copy"
                Clipboard.SetText(clickCell.Value, TextDataFormat.Text)
            Case "Paste"
                clickCell.Value = Clipboard.GetText(TextDataFormat.Text)
        End Select
    End Sub

 

Cut,Copy and paste operation on Multiple Cells of the DataGridView control

Now i will explain you how to perform cut, copy and paste operation with multiple cells of the DataGridView control. DataGridView control have a method named GetClipboardContent() and now we will use this method for set and get the values of the multiple cells to the clipboard.

Private Sub contextmenu_click(ByVal sender As System.Object, ByVal e As ToolStripItemClickedEventArgs)
        Select Case e.ClickedItem.Text
            Case "Cut"
                Dim objData As DataObject = DataGridView1.GetClipboardContent
                If objData IsNot Nothing Then
                    Clipboard.SetDataObject(objData)
                End If
                For Each cell As DataGridViewCell In DataGridView1.SelectedCells
                    cell.Value = ""
                Next
            Case "Copy"
                Dim objData As DataObject = DataGridView1.GetClipboardContent
                If objData IsNot Nothing Then
                    Clipboard.SetDataObject(objData)
                End If
        End Select
    End Sub

6 thoughts on “Add ContextMenu for each datagridview cell at run time in vb.net”

  1. Great code, thanks! And how can I use it when working with multiple cells to copy and paste. Sorry for my english, but I’m russian!

    1. Do you want to apply Cut, Copy and Paste operation for the multiple cells together?

  2. I did not understand how your code can be used for the multiple cells together?
    Please some help me understand how it is possible to implement?

    1. hello Archimeds

      you can use the cut and copy operation for the multiple cells, but how you can perform Paste operation on the multiple cells Its totally depends on you.

      However i have written the code for cut and copy over multiple cells, you can see below:

      Private Sub contextmenu_click(ByVal sender As System.Object, ByVal e As ToolStripItemClickedEventArgs)
      Dim StrData As String = ""
      For Each cell As DataGridViewCell In DataGridView1.SelectedCells
      Select Case e.ClickedItem.Text
      Case "Cut"
      StrData = StrData & " " & cell.Value
      cell.Value = ""
      Case "Copy"
      End Select
      Next
      Try
      Clipboard.SetText(StrData, TextDataFormat.Text)
      Catch ex As Exception
      End Try
      End Sub

      let me know how you can use the Paste operation on multiple cells.
      thanks

Comments are closed.