for each 循环删除控件(vb.net 2003)

来源:百度知道 编辑:UC知道 时间:2024/06/08 09:10:51
我用了两个函数,来删除我动态添加的label控件和radiobutton控件.预想是依次执行后删除容器内的所有符合条件的空间.函数如下:
Private Sub clearlabel(ByVal container As Control)
Dim ctrl As Control
For Each ctrl In container.Controls
Try
If TypeOf (ctrl) Is Label Then
container.Controls.Remove(ctrl)
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "请注意", MessageBoxButtons.OK, MessageBoxIcon.Stop)
End Try
Next
End Sub
'
Private Sub clearradiobutton(ByVal container As Control)
Dim ctrl As Control
For Each ctrl In container.Controls
If TypeOf (ctrl) Is RadioButton Then
container.Controls.Remove(ctrl)
End If
Next
End Sub

执行时调用如下:
clearradiobutton(Panel1)
clearlabel(Panel1)

因为你在删除的过程中,控件数量改变,导致循环次数不准确,所以才会不完全删除控件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace WindowsApplication14
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{

}

private void Form1_Load(object sender, EventArgs e)
{
setLabel(5);
}

private void setLabel(int num)
{
for (int i = 0; i < num; i++)
{
Label testLbl = new Label();
testLbl.Text = i.ToString();
this.Con