删除/删除动态创建的文本框

时间:2018-02-18 09:00:59

标签: c# winforms textbox controls

我有一个代码,它将在运行时创建一个文本框。

 public System.Windows.Forms.TextBox AddNewTextBox()
        {
            System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
            this.Controls.Add(txt);
            dynamicTextBoxes.Add($"tb{cLeft}", txt);
            txt.Top = cLeft * 25;
            txt.Left = 100;
            txt.Multiline = true;
            txt.Size = new System.Drawing.Size(100,100);
            txt.BringToFront();
            txt.BorderStyle = BorderStyle.None;


            txt.Text = "TextBox " + this.cLeft.ToString();
            cLeft = cLeft + 1;
            return txt;
        }

我还将控件添加到词典中

 private Dictionary<string, TextBox> dynamicTextBoxes = new Dictionary<string, TextBox>();

现在我要删除文本框。

我正在使用此代码删除/删除文本框。

dynamicTextBoxes[$"tb{cLeft - 1}"].Dispose();

但是这行代码只删除了最后创建的文本框。

我的问题是如何在每次点击按钮时逐个删除所有或选定的文本框。

1 个答案:

答案 0 :(得分:1)

首先,您需要使用Children而非Controls,其次应将控件添加到某个容器,例如GridStackPanel,...

System.Windows.Controls.TextBox txt = new System.Windows.Controls.TextBox();
yourGrid.Children.Add(txt);

请注意,名称空间应为System.Windows.Controls