0

I am using VS2012, C#, Winforms.

My application generates about 100 label controls at runtime. I want the user to right-click on a label control, bring up a context menu strip. I have this part working. But I am having trouble determining which control is being clicked on when I try to respond to a the context menu item click event. How can I pass on the control to the menu item click event?

I am using this code to determine the source control but it always causes a null exception:

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
 {
     Control sourceControl = new Control();
     sourceControl = contextMenuStrip1.SourceControl;

     MessageBox.Show(sourceControl.Text);
 }

sourceControl always get a null from contextMenuStrip1.SourceControl;

cmh2001
  • 23
  • 1
  • 7

1 Answers1

0

The SourceControl property can be null, as this property is best used during the opening event. There are a couple of workarounds available. Check these two out on StackOverflow:

ContextMenuStrip.Owner Property null When Retrieving From Nested ToolStripMenuItem

Get the SourceControl of my ContextMenuStrip when I use the shortcut key

Community
  • 1
  • 1
Chris Barlow
  • 3,274
  • 4
  • 31
  • 52