【问题标题】:Update textbox contained within a different form更新包含在不同表单中的文本框
【发布时间】:2014-03-21 01:58:21
【问题描述】:

我有 2 个表格。第二个表单是从第一个表单中的方法打开的,我希望能够更新存在于第二个表单中的文本框。

基本上我有以下代码:

    private void sendAllButton_Click(object sender, EventArgs e)
    {
        SendConsoleGUI sendOutGUI = new SendConsoleGUI();
        sendOutGUI.Show();
        sendOutGUI.sendConsoleTextBox.Text = "Test";       
    }

当我按下按钮时,第二个表单(SendConsoleGUI 表单)打开,但“测试”从未添加到其文本框中。

我在这里做错了吗?

【问题讨论】:

  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
  • 您希望从父窗体动态更新它还是仅在最初生成子窗体时更新它?如果您只想在最初生成 Child 时更新文本框,而不是将字符串作为参数传递给表单,并在 InitializeComponents 之后将文本框设置为您传递的字符串。
  • 您的代码应该可以正常工作。错误可能在其他地方。在您更新 sendConsoleTextBox.Text 的其他地方设置断点,并查看“测试”更新后是否有任何触发。

标签: c# textbox


【解决方案1】:

你需要使用invoke方法。

sendOutGUI.Invoke((MethodInvoker) delegate { sendOutGUI.sendConsoleTextBox.Text = "Test"; });

【讨论】:

    【解决方案2】:
    public partial class ParentForm : Form
    {
        public ParentForm()
        {
            InitializeComponent();
        }
        private void sendAllButton_Click(object sender, EventArgs e)
        {
            SendConsoleGUI sendOutGUI = new SendConsoleGUI("Test");
            sendOutGUI.Show();     
        }
    }
    
    public partial class ChildForm : Form
    {
        public ChildForm(string str)
        {
            InitializeComponent();
            sendConsoleTextBox.Text = str;
        }
    }
    

    如果您只希望在最初创建 ChildForm 时更新它,这将适用于您。

    【讨论】:

      猜你喜欢
      • 2010-09-06
      • 2012-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      • 1970-01-01
      • 2019-12-04
      • 1970-01-01
      相关资源
      最近更新 更多