Question

I have dynamically add Label on FlowLayoutPanel, with the following code:

private void button1_Click(object sender, EventArgs e)
    {
        Label lb = new Label();
        lb.Text = "How are You";
        lb.Size = new Size(650, Font.Height +10);
        flowLayoutPanel1.Controls.Add(lb);
        flowLayoutPanel1.SetFlowBreak(lb, true);
        lb.BackColor = Color.Wheat;
    }

In ContextMenuStrip I have add two Item Add and Edit and associate it FlowLayoutPanel, mean when user right click on the FlowLayoutPanel, Edit and Remove menu appears.

Now I want to delete the dynamically add Label using remove button (ContextMenuStrip ). I want to just right click on the desire lebel and after right click it should be removed. and the same case with Edit button for edit.

Était-ce utile?

La solution

keep a reference to your lb variable around on the form (instead of just inside the function). When you want to remove it, call flowLayoutPanel1.Controls.Remove(lb).

You should add an event handler to the label in the same sub where it is called for the label's right click event. Inside this handler is where the above call to .Remove should be.

Alternatively, since the event handler will pass the sender object in, which will be reference to the control that the event fired on, you can just call .Remove and pass in sender. you won't have to keep a reference to the label around this way unless you need it for something else.

Requested Example

flowLayoutPanel1.Controls.Remove((ToolStripMenuItem) sender);

Edited again after comments

I changed your button1's click event to

private void button1_Click(object sender, EventArgs e)
{
     lb = new Label();
    lb.Text = "How are You";
    lb.Size = new Size(650, Font.Height +10);
    flowLayoutPanel1.Controls.Add(lb);
    flowLayoutPanel1.SetFlowBreak(lb, true);
    lb.BackColor = Color.Wheat;
    lb.MouseEnter += labelEntered;
}

as you can see I added a MouseEntered event handler to catch the last label that the mouse was over.

I added the following sub, which is handler mentioned above. All it does it record the last label that the mouse was over.

private Label lastLabel;
private void labelEntered(object sender, EventArgs e)
{
    lastLabel = (Label)sender;
}

The code for the remove button has been changed to this.

public void Remove_Click(object sender, EventArgs e)
{
    if (lastLabel != null)
    {
        flowLayoutPanel1.Controls.Remove(lastLabel);
        lastLabel = null;
    }
}

First thing it does it check to make sure that lastLabel has a value, if it does it removes the last label that the mouse was over, then clears the lastLabel variable.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top