tags:

views:

96

answers:

2

I'm currently working on a project in which at one point, the user may right click a button which brings up a contextMenuStrip. I am already able to find the owner accurately from that strip, and manipulate the button clicked as follows:

Dim myItem As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
Dim cms As ContextMenuStrip = CType(myItem.Owner, ContextMenuStrip)

Dim buttonPressed As DataButton = DirectCast(cms.SourceControl, DataButton)

But now for the tricky part. Within this contextmenuStrip, I have a DropDown menu with multiple items in there. I would assume you would be able to work your way up the ladder doing casts like above in the manner of

 ToolStripDrowpDownItem > ToolStripDropDownMenu > ToolStripMenuItem > ContextMenuStrip

Unfortunately, when I try to get the sourcecontrol from this menuStrip, it return Nothing. Any ideas on how I can get the button that was pressed from this toolStripMenuItem? My current code is as follows (in which the sourceControl is Nothing)

Dim myItem As ToolStripDropDownItem = CType(sender, ToolStripDropDownItem)
Dim dropDown As ToolStripDropDownMenu = CType(myItem.Owner, ToolStripDropDownMenu)
Dim menuItem As ToolStripMenuItem = CType(dropDown.OwnerItem, ToolStripMenuItem)
Dim cms As ContextMenuStrip = CType(menuItem.Owner, ContextMenuStrip)

Dim buttonPressed As DataButton = DirectCast(cms.SourceControl, DataButton)

Any ideas on how to go about doing what I did in that first method, but just working my way up from further down the ladder?

+1  A: 

I'd suggest instead of trying to work backward to see what button was pressed and act accordingly, assign the button's behaviour when it is created.

Dim button As New ToolStripMenuItem("do something")
AddHandler button.Click, AddressOf DoSomething

Public Sub DoSomething(ByVal sender as Object, ByVal e as System.EventArgs)
    'do something
End Sub

Then you don't have to worry about it -- when it is clicked, it will do its work.

Jay
I ended up having to do a bunch of workarounds, but ultimately it was this idea that I implemented. Occam's Razor holds true once again.
AndyPerfect
A: 

Muchas gracias!!... he solucionado un problema...

queria identificar el control (picturebox) al darle clic derecho y darle en una opcion del context menu. entonces hice esto:


Dim icono As PictureBox = DirectCast(ContextMenuStrip2.SourceControl, PictureBox)

'para verificar muestro un mensaje con el nombre del control MsgBox(icono.Name)


joac