I have a foreach loop inside of an button-click event handler that I’m using to get rid of controls that all sit on the same point on the Y axis. I have a control that adds a row, and then I need users to have the option to remove a row they didn’t mean to add.
When I use the foreach loop by itself, it consistently misses two items–the same two every time. I’ve confirmed that the Y values are in fact identical. If I keep running the function, it removes all the controls on the row after three runs. However, if I nest the foreach loop, using all the same values, it works. See the code below.
This seems like a pretty sloppy way to do it, but it’s also the only solution that has worked for me. I saw a couple other posts that said to declare a second variable within the loop (i.e., Control z = c; if(z.Location....)). That didn’t make any difference in the behavior here. Can anyone explain why the foreach loop by itself isn’t working? How do I fix it without the repetitive nesting?
Working:
internal void MinButt_Click(object sender, EventArgs e)
{
Scratch.tScratch.panel2.Controls.RemoveByKey("Record" + arrDynamY[0].ToString());
foreach (Control c in Scratch.tScratch.panel2.Controls)
{
if (c.Location.Y == arrDynamY[1])
{
c.Dispose();
}
foreach (Control ctrl in Scratch.tScratch.panel2.Controls)
{
if (ctrl.Location.Y == arrDynamY[1])
{
ctrl.Dispose();
}
}
}
}
Misses the same two controls every time:
internal void MinButt_Click(object sender, EventArgs e)
{
Scratch.tScratch.panel2.Controls.RemoveByKey("Record" + arrDynamY[0].ToString());
foreach (Control c in Scratch.tScratch.panel2.Controls)
{
if (c.Location.Y == arrDynamY[1])
{
c.Dispose();
}
}
}
You should firstly obtain controls for removing and remove them afterwards like this: