使用C#添加和删除动态控件Windows窗体
我的Windows窗体表单中有三个选项卡.根据TabPages[0]
中选择的RadioButton,我在相关的TabPage上添加了一些动态控件.在Button_Click
事件上,添加了控件,但是问题是我无法从其他(不相关)TabPage中删除动态添加的控件.
I have three Tabs in my Windows Forms form. Depending on the selected RadioButton in the TabPages[0]
, I added few dynamic controls on the relevant TabPage. On the Button_Click
event the controls are added, but the problem is I'm not able to remove the dynamically added controls from the other (irrelevant) TabPage.
这是我的代码:
Label label235 = new Label();
TextBox tbMax = new TextBox();
label235.Name = "label235";
tbMax.Name = "txtBoxNoiseMax";
label235.Text = "Noise";
tbMax.ReadOnly = true;
label235.ForeColor = System.Drawing.Color.Blue;
tbMax.BackColor = System.Drawing.Color.White;
label235.Size = new Size(74, 13);
tbMax.Size = new Size(85, 20);
if (radioButton1.Checked)
{
label235.Location = new Point(8, 476);
tbMax.Location = new Point(138, 473);
tabControl.TabPages[1].Controls.Add(label235);
tabControl.TabPages[1].Controls.Add(tbMax);
tabControl.TabPages[2].Controls.RemoveByKey("label235");
tabControl.TabPages[2].Controls.RemoveByKey("tbMax");
}
else
{
label235.Location = new Point(8, 538);
tbMax.Location = new Point(138, 535);
tabControl.TabPages[1].Controls.RemoveByKey("label235");
tabControl.TabPages[1].Controls.RemoveByKey("tbMax");
tabControl.TabPages[2].Controls.Add(label235);
tabControl.TabPages[2].Controls.Add(tbMax);
}
我在哪里犯那个错误?
首先,tbMax
的名称不是"tbMax",而是"txtBoxNoiseMax".因此,对于它来说,将无法在RemoveByKey
上找到文本框.
First of all, tbMax
's name is not "tbMax", but "txtBoxNoiseMax". So for one, it won't be able to find the TextBox on RemoveByKey
.
您每次都在制作新控件.
You're making new controls each time.