user1697111 user1697111 - 3 months ago 7
Vb.net Question

Adding context_menu items dinamically with custom functions

I create context menu dinamically and want to assign menuitems to my own functions (with arguments). Unfortunatelly that dont go as I would like.

Following example illustrates what I would like to do.

Private Sub dgv_sub_CellMouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgv_sub.CellMouseUp

If e.Button = Windows.Forms.MouseButtons.Right Then
dgv_sub.Rows(e.RowIndex).Selected = True
context_sub.Items.Clear()
context_sub.Items.Add("Delete row " + dgv_sub.CurrentRow.Index.ToString, Nothing) AddressOf delRow(dgv_sub.CurrentRow.Index))
context_sub.Items.Add("Delete all rows", Nothing) , AddressOf delRow(-1))
context_sub.Show(New Point(Cursor.Position.X, Cursor.Position.Y))
End If
End Sub

Private Sub delRow(ByVal rowtodelete As Integer)

End Sub


How to make this properly and get it to work as described?

Answer

This is how I usually do these kind of things:

  1. Have a pre populated ContextMenu

  2. Assign the ContextMenu to my DataGridView

  3. Add Events on every ToolStripMenuItem

  4. In each event, first I do a check to make sure that a row has been selected

If dgv_sub.SelectedRows.Count > 0 Then

then, I get the correct row by using the

SelectedRows(0)

  1. To make things neater, you can also use the DataGridView.MouseDown event to make sure that when the user right click a row, it gets selected.

    Private Sub dgv_sub_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgv_sub.MouseDown
        If e.Button = Windows.Forms.MouseButtons.Right Then
            Dim hitTest As DataGridView.HitTestInfo
            hitTest = dgv_sub.HitTest(e.X, e.Y)
    
            If hitTest IsNot Nothing AndAlso hitTest.RowIndex > -1 Then
                dgv_sub.CurrentCell = dgv_sub.Item(hitTest.ColumnIndex, hitTest.RowIndex)
                dgv_sub.Rows(hitTest.RowIndex).Selected = True
            End If
        End If
    End Sub
    

As you need context items to be dynamic, you will have to do these in the MouseDown event aswell.

In order to add an item properly you still need a normal click event:

context_sub.Items.Add("Name of Item", Nothing, AddressOf item_Click)

Then add a Sub like this:

Private Sub item_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    'Add any logic here, you can still use the dgv_sub.SelectedRows here
End Sub

Ideally you create a different Sub for every context menu item you need to add

Comments