相关疑难解决方法(0)

我需要在处理后删除控件吗?

.NET 2

// dynamic textbox adding
myTextBox = new TextBox();
this.Controls.Add(myTextBox);

// ... some code, finally

// dynamic textbox removing
myTextBox.Dispose();

// this.Controls.Remove(myTextBox); ?? is this needed
Run Code Online (Sandbox Code Playgroud)

小解释

  • 当然,如果我处理一个控件我将不再看到它,但无论如何,在父控件集合中仍将是"Nothing"?
  • 我也需要像MSDN推荐的那样从控件中删除所有处理程序吗?

.net c# controls dispose .net-2.0

16
推荐指数
1
解决办法
5622
查看次数

为什么ControlCollection不会抛出InvalidOperationException?

按照这个问题Foreach循环处理控件跳过迭代它告诉我,迭代是允许通过更改集合:

例如,以下内容:

List<Control> items = new List<Control>
{
    new TextBox {Text = "A", Top = 10},
    new TextBox {Text = "B", Top = 20},
    new TextBox {Text = "C", Top = 30},
    new TextBox {Text = "D", Top = 40},
};

foreach (var item in items)
{
    items.Remove(item);
}
Run Code Online (Sandbox Code Playgroud)

InvalidOperationException:Collection已被修改; 枚举操作可能无法执行.

但是,在.Net表单中,您可以执行以下操作:

this.Controls.Add(new TextBox {Text = "A", Top = 10});
this.Controls.Add(new TextBox {Text = "B", Top = 30});
this.Controls.Add(new TextBox {Text = "C", Top = 50});
this.Controls.Add(new …
Run Code Online (Sandbox Code Playgroud)

.net c# foreach invalidoperationexception winforms

11
推荐指数
1
解决办法
217
查看次数

foreach控制c#跳过控件

我有以下循环来删除我的C#Windows窗体应用程序中的按钮.唯一的问题是它会跳过其他所有按钮.如何从表单中删除所有按钮控件?

foreach (Control cntrl in Controls)
{
    if(cntrl.GetType() == typeof(Button))
    {
        Controls.Remove(cntrl);
        cntrl.Dispose();
    }
}
Run Code Online (Sandbox Code Playgroud)

c# foreach controls enumeration winforms

6
推荐指数
1
解决办法
1465
查看次数