1

I have some dynamically created PictureBox's and a ContextMenu with a ToolStripMenuItem named "Remove" ... I want to remove only the PictureBox that is clicked but this ContextMenu is attached to all PictureBox's.

How to do it ? And please explain because I am still a beginner.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
Paradox
  • 91
  • 1
  • 8

1 Answers1

3

You have to follow the chain of menu owners until you get to the control:

private void RemoveMenuItem_Click(object sender, EventArgs e) {
  ToolStripMenuItem ti = sender as ToolStripMenuItem;
  ContextMenuStrip cs = ti.Owner as ContextMenuStrip;
  PictureBox pb = cs.SourceControl as PictureBox;
  MessageBox.Show(pb.Name);  // or pb.Dispose();
}

This code isn't doing any error checking. You should check to see if any of those variables are null before trying to access any of its properties.

Cody Gray gave a comprehensive answer here: Determine what control the ContextMenuStrip was used on

Community
  • 1
  • 1
LarsTech
  • 80,625
  • 14
  • 153
  • 225