从表中动态删除控件

时间:2014-08-04 14:02:18

标签: c# winforms

尝试删除文本框和标签,而其名称与列表框中的所选项目具有相同的值。如果我运行此代码,则仅执行第一个if语句,并仅删除表中的标签控件。

我还必须提到表的控件是动态创建的。

    private void pictureBox2_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < listBox2.SelectedItems.Count; i++)
        {
            foreach (Control t in table2.Controls)
            {
                if (t is Label && t.Text==listBox2.SelectedItem.ToString())
                {
                    table2.Controls.Remove(t);
                    continue;
                }
                if (t is TextBox && t.Name.Contains(listBox2.SelectedItem.ToString()))
                {
                    table2.Controls.Remove(t); continue;
                }
            }
            listBox2.Items.Remove(listBox2.SelectedItems[i]); i--;
        }
    }

这就是在表格中创建控件的方式。

    private void pictureBox1_Click(object sender, EventArgs e)
    {
        listBox2.Items.Clear();
        this.table2.Controls.Clear();
        foreach (var item in listBox1.SelectedItems)
        {
          table2.Controls.Add(new Label() { Name = item.ToString(), Text = item.ToString(), AutoSize = true });
          table2.Controls.Add(new TextBox() { Name = item.ToString(), AutoSize = true });
            }
        }
    }

2 个答案:

答案 0 :(得分:2)

从集合中移除项目时(假设位置0处的项目),下一个位置(位置1)的项目在零位置移动。但是你的for循环执行下一次迭代,你的索引器变为1,因此它终止循环。

避免这种情况的第一种方法是以相反的顺序循环,从集合的末尾开始到它的开始

但你也可以用

简化你的代码
private void pictureBox2_Click(object sender, EventArgs e)
{
    for (int i = listBox2.SelectedItems.Count - 1 ; i >= 0 ; i--)
    {
        // This is our search term...
        string curItem = listBox2.SelectedItems[i].ToString();

        // Get only the controls of type Label with Text property equal to the current item
        var labels = table2.Controls
                     .OfType<Label>()
                     .Where (c => c.Text == curItem)
                     .ToList();
       if(labels != null)  
       {
          for(int x = labels.Count()-1; x >= 0; x--)
             table2.Remove(labels[x]);
       }


       // Get only the controls of type TextBox with Name property containing the current item
       var boxes = table2.Controls
                          .OfType<TextBox>()
                          .Where (c => c.Name.Contains(curItem)
                          .ToList();

       if(boxes != null)  
       {
          for(int x = boxes.Count()-1; x >= 0; x--)
             table2.Remove(boxes[x]);
       }
       listBox2.Items.Remove(curItem); 
    }
}

答案 1 :(得分:1)

为什么在for循环结束时递减迭代器?看起来你好像陷入了困境,伙计。