【问题标题】:Delete/Remove the Dynamically created Textboxes in Windows Application [duplicate]删除/删除 Windows 应用程序中动态创建的文本框 [重复]
【发布时间】:2018-02-18 09:00:58
【问题描述】:

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

 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();

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

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

【问题讨论】:

  • 错误信息是什么?
  • @EhsanSajjad Page 2 不包含任何“控件”定义,并且没有扩展方法“控件”接受 page2 类型的第一个参数可以正常(您是否缺少指令或参考)
  • “当我在 WPF 中使用 System.Windows.Forms. ... 时”——这就是问题所在。
  • 你认为错误信息在哪些方面没有用
  • WPF 窗口没有 Controls 属性。嵌入 winforms 控件需要 WindowsFormsHost。支持 winforms 文本框而不是 WPF 文本框的实际理由很少,您需要抛出心理开关并开始编写 WPF 代码。

标签: c# winforms textbox controls


【解决方案1】:

首先,您需要使用Children 而不是Controls,其次您应该向一些容器添加控件,例如Grid,StackPanel,...

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

请注意这里的命名空间应该是System.Windows.Controls

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 2011-08-14
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多