foreach循环用于处置控制跳过迭代 [英] Foreach loop for disposing controls skipping iterations
问题描述
代码来创建文本框...
Code to create textboxes...
private void btnAddIncrement_Click(object sender, EventArgs e)
{
SmartTextBox dynamictextbox = new SmartTextBox();
dynamictextbox.BackColor = Color.Bisque;
dynamictextbox.Width = this.tbWidth;
dynamictextbox.Left = (sender as Button).Right + this.lastLeft;
dynamictextbox.K = "Test";
this.lastLeft = this.lastLeft + this.tbWidth;
dynamictextbox.Top = btnAddStart.Top;
this.Controls.Add(dynamictextbox);
}
代码删除所有文本框。
Code for to remove all text boxes.
foreach (Control c in this.Controls)
{
if (c.GetType() == typeof(BnBCalculator.SmartTextBox))
{
count++;
//MessageBox.Show((c as SmartTextBox).K.ToString());
c.Dispose();
}
// else { MessageBox.Show("not txtbox"); }
}
When I click the btnAddIncrement I get the following as expected...
但是当我点击重置它错过每一秒文本框。请参见下面...
But when I click reset it misses every second textbox. See below...
不知道这是怎么回事在这里,但这个是相同的,无论怎么可能文本框我想补充。它总是错过每一秒框。
No idea what's going on here but this is the same no matter how may text boxes I add. It always misses every second box.
推荐答案
您应该使用反向标准的for循环,从它的容器处置SmartTextBoxes
You should use a reverse standard for loop to dispose the SmartTextBoxes from its container
for(int x = this.Controls.Count - 1; x >= 0; x--)
{
BnBCalculator.SmartTextBox c = this.Controls[x] as BnBCalculator.SmartTextBox;
if (c != null)
{
count++;
c.Dispose();
}
}
的根据这个问题/答案你不需要从容器当然这中删除它们避免了两个循环(明确或隐含)。另外,在接受的答案,你可以看到为什么你的代码就会每隔一两个控制的原因。
According to this question/answer you don't need to remove them from the container and of course this avoids two loops (explicit or implicit). Also in the accepted answer you could see the reason why your code jumps a control every two.
if (parent != null)
{
parent.Controls.Remove(this);
}
这要处置是从你迭代集合中删除控制过度。 (不清楚为什么这并不抛出标准除外)。
The control that you want to dispose is removed from the collection that you are iterating over. (Not clear why this doesn't throw the standard exception).
而不是一个简单的循环反向避免在有序进入处置控制的任何问题。
Instead looping with a simple for in reverse avoid any problem in the ordered access to the controls to dispose.
这篇关于foreach循环用于处置控制跳过迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!