Winforms remove controls on click

143 views Asked by At

In my application I am generating some controls dynamically. On telerik menu control when I click I want to remove those controls and add new controls. I am using the following code. It is removing the controls but only one control per click. Why this code is not removing all the controls at one time?

private void radMenuItem3_Click(object sender, EventArgs e)
{
    foreach (Control ctrl in rpvRecord.Controls)
    {
        ctrl.Dispose();
    }
}
3

There are 3 answers

1
Nathan M. On BEST ANSWER

The issue is that you are deleting the control out of the collection that you are iterating through, which causes a change in the collection and causes the loop to fail. I would suggest using a different style of loop to accomplish this. For example:

private void radMenuItem3_Click(object sender, EventArgs e)
{
    while (rpvRecord.Controls.Count > 0)
    {
        ctrl = rpvRecord.Controls[0];
        rpvRecord.Controls.Remove(ctrl);
        ctrl.Dispose();
    }
}

Hope this helps!

0
B Wells On

Probably need to remove the item from the collection, and, you might be altering your collection count as you go through the loop by doing a foreach. You might want to iterate from rpvRecord.Controls.Count - 1 to 0 with i-- like this:

private void radMenuItem3_Click(object sender, EventArgs e)
{
    for (var i = rpvRecord.Controls -1; i >= 0; i --)
    {
        ctrl = rpvRecord.Controls[i];
        rpvRecord.Controls.Remove(cntrl);
        ctrl.Dispose();
    }
}
0
Hamid Pourjam On

if you want to remove all controls at once you can just use Clear() method

private void radMenuItem3_Click(object sender, EventArgs e)
{
   rvpRecord.Controls.Clear();
}