【问题标题】:Remove the Labels after draw them dynamically动态绘制标签后移除标签
【发布时间】:2014-05-12 05:51:01
【问题描述】:

我正在动态绘制一组标签,我想删除它们。我正在使用相同的按钮来删除和添加新标签。标签是使用随机坐标随机绘制的。但是,当我按下按钮时,我应该删除旧标签并出现新标签。但是,我所拥有的是新标签出现,旧标签出现但空标签。我希望它们被完全删除。看图:

//Global Intialization
int xCoor;
int yCoor;

//send the random method
Random coor = new Random();

private void btnRun_Click(object sender, EventArgs e) 
{
    //Removing the Labels after drawing them in the picBox
    this.RemoveOldLabels();

    //to  draw the Labels rendomely.
    for (int x = 1; x <= 25; x++)
    {
        for (int i = 0; i < 1; i++)
        {
            //Get the Coordinates for X,Y 
            xCoor = coor.Next(0, 750);
            yCoor = coor.Next(0, 500);

            //Start Greating the Labels
            Label nodeLabel1 = new Label();

            nodeLabel1.Text = x + " : " + xCoor + "," + yCoor;
            nodeLabel1.AutoSize = true;
            nodeLabel1.Location = new Point(xCoor + 10, yCoor + 5);
            nodeLabel1.ForeColor = System.Drawing.Color.Red;
            nodeLabel1.BackColor = Color.LightBlue;

            //Draw the Labels in the PicBox
            this.picNodes.Controls.Add(nodeLabel1);
        }
    }
}

//this to  remove the Labels 
private void RemoveOldLabels()
{
    List<Label> LabelsToRemove = new List<Label>();

    foreach (var x in this.picNodes.Controls)
    {
        if (x.GetType() == typeof(System.Windows.Forms.Label))
        {
            LabelsToRemove.Add((Label)x);
        }
    }

【问题讨论】:

  • 为什么不创建一个标签列表并将创建的标签添加到列表中,然后在 RemoveOldLabels 中将它们全部删除?
  • 因为我以后会有随机数的标签。
  • 我不明白 - 你的意思是你的名字中会有随机数字还是......?
  • 我每次都会有随机数量的标签。

标签: c# winforms


【解决方案1】:

看起来RemoveOldLabels() 正在查找标签,但实际上并未删除它们。

尝试获取所有“标签”控件,然后处理它们(这也应该将它们从集合中删除并使它们从表单中消失)

foreach (var label in picNodes.Controls.OfType<Label>().ToList())
    label.Dispose();

【讨论】:

【解决方案2】:

您的删除旧标签逻辑不会执行任何操作。它只是将标签添加到列表中,仅此而已。

您需要从 picNodes 中删除这些控件,如下所示:

  private void RemoveOldLabels()
  {
    List<Label> LabelsToRemove = new List<Label>();

    foreach (var x in this.picNodes.Controls)
    {
        if (x.GetType() == typeof(System.Windows.Forms.Label))
        {
            LabelsToRemove.Add((Label)x);
        }
    }

    foreach (var label in LabelsToRemove)
    {
        this.picNodes.Controls.Remove(label);
        label.Dispose();
    }
  }

【讨论】:

  • 有更简洁的方法来编写上面的代码(使用 LINQ),但我已尽可能重用您现有的代码和命名。
  • 请按3次按钮
  • 他们没有删除以前的标签。
  • 我刚刚对此进行了测试,并且使用您的代码进行了上述修改,它可以正常工作。每次都会删除所有旧标签,并随机出现新标签。不知道我还能建议什么 - 确保您没有任何其他代码向 picNodes 添加标签。
猜你喜欢
  • 2018-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
相关资源
最近更新 更多