【发布时间】:2023-03-15 13:22:01
【问题描述】:
我正在尝试删除在运行时在 tabPage 上创建的按钮。我创建了一个函数,它应该通过该 tabPage 上的所有控件,但由于某种原因,每次调用它时只有一半的按钮被删除。 (页面有8个按钮,我要全部删除)
foreach(var ctr in tabControl.SelectedTab.Controls)
{
if (ctr is Button)
{
if (ctr is Button) { tabControl.SelectedTab.Controls.Remove((Button)ctr); }
}
}
我什至尝试了以下操作,但遇到了同样的问题,
for (int i = 0; i < 8; i++)
{
tabControl.SelectedTab.Controls.Remove(
((Button)tabControl.SelectedTab.Controls[i]));
}
但是,当我尝试调试时,它只识别在 tabPage 上制作的第 1、3、5 和 7 个按钮,并且只删除它们,留下 4。如果我再次尝试这样做,它会删除一半, 留下2。我初始化每个按钮如下。
for (int i = 0; i < 8; i++)
{
tempButton[i] = new Button();
tabControl.SelectedTab.Controls.Add(tempButton[i]);
tempButton[i].AutoSize = true;
tempButton[i].Location = new System.Drawing.Point(
100 + (150 * (i % 4)), 175 + (175 * (int)(.25 * i)));
//tempButton[i].Name = "tempButton" + i.ToString();
tempButton[i].Text = names[i];
tempButton[i].Size = new System.Drawing.Size(35, 13);
tempButton[i].TabIndex = i;
}
【问题讨论】: