3

在我的程序中生成按钮之前,应该使用以下方法清除它们:

for (int i = 0; i < buttons.Length; i++)
    this.Controls.Remove(buttons[i]);

但是,上一代的所有按钮都保留了下来。这可能是什么原因造成的?

(下面是整个函数,其他函数中numButton的变化。)

    int numButtons = 5;
    Button[] buttons = new Button[10];

    private void generate_buttons()
    {
        for (int i = 0; i < buttons.Length; i++)
        {
            this.Controls.Remove(buttons[i]);
        }
        for (int i = 0; i < numButtons; i++)
        {
            buttons[i] = new Button();
            buttons[i].Name = "btn" + i.ToString();
            buttons[i].Text = Convert.ToString(i + 1);
            buttons[i].Size = new Size(40, 24);

            int yOffset = 40;
            int xOffset = 20 + i * 42;
            buttons[i].Location = new Point(xOffset, yOffset);
            buttons[i].BackColor = System.Drawing.SystemColors.Control;
            buttons[i].Enabled = false;
            buttons[i].Click += new EventHandler(this.clickMe);
            buttons[i].Visible = true;
            this.Height = yOffset + 104;
            this.Width = xOffset + 75;
        }
        Controls.AddRange(buttons);
    }
4

2 回答 2

3

尽管您要从控件集合中删除按钮,但您并没有从buttons数组中删除它。添加

Array.Clear(buttons, 0, buttons.Length);

我还修改了删除循环,以显式处理按钮持有的任何资源,如MSDN 上所示。

for (int i = 0; i < buttons.Length; i++)
{
    //you can change break to 'continue' if you remove buttons
    //from the array randomly so that if it encounters a null 
    //it will carry on reading the rest of the array.
    if (buttons[i] == null)
        break;  


    //dispose any button resources and event handlers so no references remain
    buttons[i].Click -= new EventHandler(this.clickMe);
    this.Controls.Remove(buttons[i]);
    buttons[i].Dispose(); 
}

Array.Clear(buttons, 0, buttons.Length);

//..
于 2013-04-14T00:24:55.520 回答
-2

考虑改用通用列表集合。这允许您使用 .Add() 和 .Remove()/.RemoveAt() 方法更轻松地添加和删除元素。

教程/示例: http: //www.dotnetperls.com/list

于 2013-04-14T00:09:55.453 回答