开发者

Adding and removing dynamic controls Windows Forms using C#

开发者 https://www.devze.com 2022-12-28 06:08 出处:网络
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 a

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.

Here's my code:

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.Locatio开发者_开发技巧n = 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);
}

Where am I making that mistake?


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.


As lc already mentioned:

You named your TextBox variable tbMax, but you gave it the name txtBoxNoiseMax. If you take a look into the description of RemoveByKey, you'll see it works on the Name property. So you should change

tbMax.Name = "txtBoxNoiseMax";

into

tbMax.Name = "tbMax";
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号