4

I have single ContextMenuStrip attached to two controls (DataGridView).
In the ToolStripMenuItem click event, I manage to get the original caller (the DataGridView) with this code :

var menu = (ToolStripDropDownItem)sender;
var strip = (ContextMenuStrip)menu.Owner;
var dgv = (DataGridView)strip.SourceControl;  

It works pretty good when I click on my ToolStripMenuItem.
But when I use the sortcut key linked to the ToolStripMenuItem, the strip.SourceControl return null.
Does anyone know why ?

Bastardo
  • 4,144
  • 9
  • 41
  • 60
Nicolas
  • 6,289
  • 4
  • 36
  • 51
  • Maybe because you have tow datagridview and one menu So when you used a shortcut the event didn't know what datagridview fire the event, you can try set different shortcut for each datagrid or different menus – AlaaL Apr 14 '11 at 14:55
  • The shortcut is a property of the ToolStripMenuItem. As there is only one ToolStripMenuItem I can't set different shortcuts. A solution could be to create two menus, but I would like to know why there is this behaviour. – Nicolas Apr 14 '11 at 15:14

1 Answers1

5

The SourceControl property shows the control that caused the ContextMenuStrip to open. Since in this case the ContextMenuStrip doesn't display there is no control used to open it, and thus the property is null.

This property is better used in the context of the opening event. See ContextMenuStrip.SourceControl.

Update: One method to figure out which DataGridView was the intended receiver of the ToolStripMenuItem click would be to see which one has the focus:

var dgv = this.ActiveControl as DataGridView;
if ( dgv != null) // make sure to check for null before trying to use this var
    //...
msergeant
  • 4,771
  • 3
  • 25
  • 26
  • Thanks for your precision on the SourceControl property. But how can I get the control that owns the ContextMenuStrip when I use a shortcut key ? – Nicolas Apr 19 '11 at 08:56
  • I added a way to check for the DataGridView that has the focus. If the focus is not on one of the DataGridView, there may not be a way to tell which one the user was targeting. – msergeant Apr 19 '11 at 13:28
  • 1
    The ActiveControl property is a good idea. Unfortunately my DataGridViews are in a SplitContainer, and the ActiveControl property returns me the SplitContainer. – Nicolas Apr 20 '11 at 13:13
  • SplitContainer also has ActiveControl, since it is ContainerControl, just like Form or UserControl classes. In this case you could do: `SplitContainer container = this.ActiveControl as SplitContainer; DataGridView dgv = container.ActiveControl as DataGridView;` – Alex Sep 09 '13 at 13:35