C# - 将文本从 Form1 的文本框中加载到 Form2 的文本框中

C# - Load Text from Textbox in Form1 into Textbox in Form2

快点!

由于物理上没有 space 用于更多文本框,因此我不得不向我的 windows 表单应用程序添加第二个表单。 一些文本框最终与原始表格相同(我知道这不理想,但两种表格各自写入单独的文本文件,因此总体上更容易)

在这种情况下,我希望将原始表单中文本框中的值复制到第二个表单中的重复文本框中(试图防止重复数据输入并降低错误风险)。

因此,我在第一个 (Form1) 表单上单击一个按钮,调用 .Show() 函数以加载第二个表单 (PreAnaestheticChecklist) 的新版本。

    public void btnPreOpChecklist_Click(object sender, EventArgs e)
    {
        //create secondary form for pre-anaesthetic checklist
        PreAnaestheticChecklist checklistForm = new PreAnaestheticChecklist();

        //load pre-anaesthetic checklist form to screen
        checklistForm.Show();
    }

这工作正常,表单加载为空白。我写了一大堆小字符串函数,这些函数 return 由 form1 文本框中的文本组成的字符串。这些在 PreAnaestheticChecklist_Load 事件中调用。下面以其中一个传输为例显示了一个示例。

    public string getProcedure()
    {
        //load value from textbox in IOconsole
        string proc = main.txtProcedure.Text;
        //return this to textbox on Checklist
        return proc;
    }

    public void PreAnaestheticChecklist_Load(object sender, EventArgs e)
    {
        //load any values already on main form into respective textboxes
        txtProcName.Text = getProcedure();
        txtPlannedProc.Text = getProcedure();
    }

这是为另外几个文本框完成的,但即使如此,第二个表单加载时仍为空白。

我阅读并被建议尝试将 _Load 事件中的所有文本框分配放入加载 form2 的按钮单击事件中,但仍然没有。 我还将所有形式的修饰符 属性 更改为 'Public',但仍然没有!

不确定下一步要看哪里,所以非常感谢任何帮助解决这个问题!

提前致谢, 马克

调用 Show() 时,将 Form1 作为 Owner 传入:

public void btnPreOpChecklist_Click(object sender, EventArgs e)
{
    //create secondary form for pre-anaesthetic checklist
    PreAnaestheticChecklist checklistForm = new PreAnaestheticChecklist();

    //load pre-anaesthetic checklist form to screen
    checklistForm.Show(this); // <-- passing in the Owner
}

现在,在您的 PreAnaestheticChecklist 表单的 Load() 事件中,将 .Owner 属性 转换为 Form1 并将其存储在您的 "main" 变量中:

public void PreAnaestheticChecklist_Load(object sender, EventArgs e)
{
    this.main = (Form1)this.Owner;

    //load any values already on main form into respective textboxes
    txtProcName.Text = getProcedure();
    txtPlannedProc.Text = getProcedure();
}