我有一个名为pan_items的面板和两个名为btn_fresh和btn_next的按钮。我使用'fresh'来加载一组选项,'next'来改变选项。选项显示为radiobuttons,我以编程方式添加和删除。我的代码添加radiobutton控件没有问题,但当我尝试删除它时,它随机删除一些并留下一些。这是我的代码
private void btn_fresh_Click(object sender, EventArgs e)
{
this.index = 0;
int i = 0;
foreach (string str in options[index])
{
RadioButton rdb = new RadioButton();
rdb.Text = str;
rdb.Name = str + "_" + i++;
rdb.Location = new Point(20, i * 20);
pan_items.Controls.Add(rdb);
}
btn_fresh.Enabled = false;
btn_next.Enabled = true;
}
private void btn_next_Click(object sender, EventArgs e)
{
foreach (Control ctrl in pan_items.Controls.OfType<RadioButton>())
{
if (((RadioButton)ctrl).Checked)
MessageBox.Show(ctrl.Name + " " + ctrl.Text + " is checked!");
pan_items.Controls.Remove(ctrl);
this.Controls.Remove(ctrl);
ctrl.Dispose();
}
this.index += 1;
int i = 0;
foreach (string str in options[index])
{
RadioButton rdb = new RadioButton();
rdb.Text = str;
rdb.Name = str + "_" + i++;
rdb.Location = new Point(20, i * 20);
pan_items.Controls.Add(rdb);
}
btn_previous.Enabled = true;
}
有什么问题,如何纠正?
非常感谢,从重复的链接中得到了答案。这段代码工作
private void btn_next_Click(object sender, EventArgs e)
{
for (int j = pan_items.Controls.OfType<RadioButton>().Count() - 1; j >= 0; --j)
{
var ctrl = pan_items.Controls[j];
if (((RadioButton)ctrl).Checked)
MessageBox.Show(ctrl.Name + " " + ctrl.Text + " is checked!");
pan_items.Controls.Remove(ctrl);
this.Controls.Remove(ctrl);
ctrl.Dispose();
}
this.index += 1;
int i = 0;
foreach (string str in options[index])
{
RadioButton rdb = new RadioButton();
rdb.Text = str;
rdb.Name = str + "_" + i++;
rdb.Location = new Point(20, i * 20);
pan_items.Controls.Add(rdb);
}
btn_previous.Enabled = true;
}