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 ?
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
//...