Adding and removing dynamic controls Windows Forms using C#

给你一囗甜甜゛ 提交于 2020-02-06 05:44:32

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/2688915/adding-and-removing-dynamic-controls-windows-forms-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!