使用C#添加和删除动态控件Windows窗体 [英] Adding and removing dynamic controls Windows Forms using C#

查看:513
本文介绍了使用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.

这篇关于使用C#添加和删除动态控件Windows窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆