1
votes

In my program, I generate Labels dynamically by right click -> new in the form:

private Point MouseDownLocation;
private List<Label> labelList=new List<Label>();

private void mainContextMenu_Opening(object sender, CancelEventArgs e)
{
  MouseDownLocation = PointToClient(MousePosition);
}

private void valueToolStripMenuItem_Click(object sender, EventArgs e)
{
  Label label = new Label();
  label.Location = MouseDownLocation;
  label.AutoSize = true;
  label.ContextMenuStrip = valueContextMenu;
  label.Text = "test";
  this.Controls.Add(label);
  labelList.Add(label);
}

Next I have the valueContextMenu with the Button Delete with which I want to be able to rightclick such a generated label and then delete.

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
}

the problem is, that in this function(which is being called), there is no way of retrieving the label the menu was called on, since sender is the contextmenu..

1

1 Answers

0
votes

Try examining the SourceControl property of the ContextMenuStrip:

private void deleteToolStripMenuItem_Click(object sender, EventArgs e) {
  Control c = ((ContextMenuStrip)((ToolStripMenuItem)sender).Owner).SourceControl;
  if (c != null) {
    // do something...
  }
}