2

我在FlowLayoutPanel上动态添加了Label,代码如下:

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;
    }

ContextMenuStrip我添加了两个 Item Add 和 Edit 并将其关联FlowLayoutPanel,这意味着当用户右键单击FlowLayoutPanel时,会出现 Edit 和 Remove 菜单。

现在我想使用删除按钮(ContextMenuStrip)删除动态添加标签。我只想右键单击欲望标签,右键单击后应该将其删除。与编辑按钮相同的情况进行编辑。

4

1 回答 1

3

在表单上保留对 lb 变量的引用(而不是在函数内部)。当你想删除它时,调用 flowLayoutPanel1.Controls.Remove(lb)。

您应该将事件处理程序添加到标签的右键单击事件调用的同一子中的标签。在这个处理程序内部是上面对 .Remove 的调用应该在的地方。

或者,由于事件处理程序将传入 sender 对象,该对象将引用触发事件的控件,因此您只需调用 .Remove 并传入 sender。除非您需要它用于其他用途,否则您不必以这种方式保留对标签的引用。

请求的示例

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

评论后再次编辑

我将您的 button1 的点击事件更改为

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;
}

如您所见,我添加了一个 MouseEntered 事件处理程序来捕获鼠标经过的最后一个标签。

我添加了以下子,即上面提到的处理程序。它所做的就是记录鼠标经过的最后一个标签。

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

删除按钮的代码已更改为此。

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

它首先检查以确保 lastLabel 有一个值,如果这样做,它会删除鼠标经过的最后一个标签,然后清除 lastLabel 变量。

于 2011-10-25T04:17:55.867 回答