i am attaching a single context menu to multiple text box. so, i need to get the control name/reference that used to show the context menu.
below is the sample image of
If you check this C# thread the accepted answer notes it is a bug. The workaround presented there uses a private variable to store the SourceControl
on the Opening
event of the ContextMenuStrip
. I've converted to VB.NET and used the Tag
of the ContextMenuStrip
instead of using the variable. You then refer to the Tag
property instead of the faulty SourceControl
property:
Imports System.ComponentModel
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.TextBox1.ContextMenuStrip = Me.ContextMenuStrip1
Me.TextBox2.ContextMenuStrip = Me.ContextMenuStrip1
End Sub
Private Sub ContextMenuStrip1_Opening(sender As Object, e As CancelEventArgs) Handles ContextMenuStrip1.Opening
Me.ContextMenuStrip1.Tag = CType(Me.ContextMenuStrip1.SourceControl, Control)
End Sub
Private Sub TestToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles TestToolStripMenuItem.Click
' first level of context menu strip
Dim Strip As ContextMenuStrip = CType(sender, ToolStripMenuItem).Owner
Dim Box As TextBox = Strip.Tag
MessageBox.Show(Box.Name)
End Sub
Private Sub ChildToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ChildToolStripMenuItem.Click
' second level of context menu strip
Dim Strip As ContextMenuStrip = CType(sender, ToolStripMenuItem).OwnerItem.Owner
Dim Box As TextBox = Strip.Tag
MessageBox.Show(Box.Name)
End Sub
End Class