views:

578

answers:

2

I have three Tabs in my WinForm; depending on the selected RaioButton in the TabPages[0] I added few dynamic controls on the relevant TabPage. On Button_Click event the controls are added, but the prob is the 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?????

+1  A: 

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.

I'm also not 100% sure, but I believe controls can only have one parent, and thus can only live in one container at a time. This could be causing troubles in the true part of your if statement, since you are adding controls to another container before removing them first.

Scrap what I said above, I just reread your code and you're making new controls each time.

lc
Thx... the error is corrected now :)
gsvirdi
A: 

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