Reputation: 91
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.
Upvotes: 1
Views: 295
Reputation: 81675
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
Upvotes: 3