gsvirdi
gsvirdi

Reputation: 426

Adding and removing dynamic controls Windows Forms using C#

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.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);
}

Where am I making that mistake?

Upvotes: 1

Views: 11134

Answers (2)

lc.
lc.

Reputation: 116528

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.

Upvotes: 1

Oliver
Oliver

Reputation: 45109

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";

Upvotes: 0

Related Questions