简体   繁体   中英

Removing Dynamically created controls in Panel

I have spent hours trying to understand what is the problem in my coding but without any much result. Hence thought of posting here for an explanation

In my UI design, I have first row of <<checkbox, textbox, textbox>> in this order. And depending on the number of rows of result returned, I will dynamically create the same number of rows of checkbox and textboxes.

However when I try to remove the redundant rows, leaving only row 1 intact, I noticed that only some controls are being removed.

For eg

Before deleted:

checkbox0 textbox0 tb0

checkbox1 textbox1 tb1

checkbox2 textbox2 tb2

After executing

checkbox0 textbox0 tb0

--------- -------- tb1

checkbox2 textbox2 ---

My code for removing is as below:

foreach (Control c in panel1.Controls)
{                
  lastChar = c.Name[c.Name.Length - 1];
  lastValue = (int)Char.GetNumericValue(lastChar);
  MessageBox.Show("second " + c.Name);

  if (lastValue > 0 && lastValue < count)
  {
    panel1.Controls.Remove(c);
    c.Dispose();
  }
 }

Rightfully foreach will run through all the controls within the panel1. But i noticed that once the Remove statement is in, the whole operation went haywire.

You can not add or remove items into/from a IEnumerable inside a foreach loop. Instead try using a for loop. Check this . Actually the exception you are receiving should be telling you this.

for (int i = 0; i < panel1.Controls.Count; i++)
{                
  Control c = panel1.Controls[i];
  lastChar = c.Name[c.Name.Length - 1];
  lastValue = (int)Char.GetNumericValue(lastChar);
  MessageBox.Show("second " + c.Name);

  if (lastValue > 0 && lastValue < count)
  {
    panel1.Controls.Remove(c);
    c.Dispose();
    i--;
  }
 }

You can shorten @Adi's code slightly with:

        for (int i = panel1.Controls.Count - 1; i >= 0; i--)
        {
            Control c = panel1.Controls[i];
            lastValue = (int)Char.GetNumericValue(c.Name, c.Name.Length - 1);
            if (lastValue > 0 && lastValue < count)
            {
                c.Dispose();
            }
        }

Note the overload of GetNumericValue() to directly get your desired character value, and you only need to dispose of the control as this will automatically remove it from the container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM