Delete/Remove Windows 应用程序中动态创建的文本框
Delete/Remove the Dynamically created Textboxes in Windows Application
我有一个代码可以在运行时创建一个文本框。
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>();
现在我想删除文本框。
我正在使用此代码 delete/remove 文本框。
dynamicTextBoxes[$"tb{cLeft - 1}"].Dispose();
但是这行代码只删除了最后创建的文本框。
我的问题是如何在每次单击按钮时一个一个地删除所有或选定的文本框。
首先,您需要使用 Children
而不是 Controls
,其次,您应该向某些容器添加控件,例如 Grid
、StackPanel
、...
System.Windows.Controls.TextBox txt = new System.Windows.Controls.TextBox();
yourGrid.Children.Add(txt);
请注意这里的命名空间应该是System.Windows.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>();
现在我想删除文本框。
我正在使用此代码 delete/remove 文本框。
dynamicTextBoxes[$"tb{cLeft - 1}"].Dispose();
但是这行代码只删除了最后创建的文本框。
我的问题是如何在每次单击按钮时一个一个地删除所有或选定的文本框。
首先,您需要使用 Children
而不是 Controls
,其次,您应该向某些容器添加控件,例如 Grid
、StackPanel
、...
System.Windows.Controls.TextBox txt = new System.Windows.Controls.TextBox();
yourGrid.Children.Add(txt);
请注意这里的命名空间应该是System.Windows.Controls
。