Wine Too
Wine Too

Reputation: 4655

How to determine which control opens ContextMenuStrip

In my form I have MenuStrip, ContextMenuStrip and DataGridView.
This same ContextMenuStrip is attachetd to one MenuStripItem as "DropDown" and to DataGridView as "ContextMenuStrip". That works good.

Problem is that I have to know what is opening that ContextMenuStrip (MeuStripItem or DataGridView) so I can hide some Items depending on that.

This is my approach where I try to determine if caller is MenuStrip1 which don't work.

   Private Sub mycontextmenu_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles mycontextmenu.Opening

       If CType(sender, MenuStrip) Is MenuStrip1 Then
          ExitToolStripMenuItem.Visible = False
       Else
          ExitToolStripMenuItem.Visible = True
       End If
   End Sub

Here error message appears: Unable to cast object of type 'System.Windows.Forms.ContextMenuStrip' to type 'System.Windows.Forms.MenuStrip'.
Please help to solve described problem.

Upvotes: 0

Views: 303

Answers (1)

ThatGuy
ThatGuy

Reputation: 228

sender is going to be the context menu strip the source control property will retrieve the owner instance

Private Sub mycontextmenu_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles mycontextmenu.Opening

   If mycontextmenu.SourceControl is MenuStrip1 Then
      ExitToolStripMenuItem.Visible = False
   Else
      ExitToolStripMenuItem.Visible = True
   End If

End Sub

Upvotes: 2

Related Questions