将数据返回到 Forms 而不打开新实例
我试图将一些数据从 Form2 返回到 Form1,一切看起来都很好,我得到了数据,但是,当我尝试将数据传递到文本框时,它不会更改文本。仅当我打开 Form1 的新实例时,它才可以在 Form2 上运行。为什么会发生这种情况?我无法将文本发送到旧实例吗?
我正在使用这段代码;
Form1(主窗体)
public void updateText(string data)
{
MessageBox.Show(data);
txtGood.Text = data;
}
Form2 SecondaryForm = new Form2();
SecondaryForm.ShowDialog();
Form2(带有用户数据的第二个窗体)
Form1 MainForm = new Form1();
MainForm.updateText(data);
MainForm.ShowDialog();
this.Close();
那么,我的问题是,如何将数据值传递给主窗体的旧实例?无需创建新实例并显示新实例。有办法做到这一点吗?
I am trying to return some data from Form2 to Form1, everything seems fine, I got the data and so, but, when I try to pass my data to a textbox, it doesn't changes the text. Only if I open a new instance of Form1, on Form2 it works. Why this happen? Can't I send the text to the old instance?
I'm using this code;
Form1 (Main Form)
public void updateText(string data)
{
MessageBox.Show(data);
txtGood.Text = data;
}
Form2 SecondaryForm = new Form2();
SecondaryForm.ShowDialog();
Form2 (Second Form with user data)
Form1 MainForm = new Form1();
MainForm.updateText(data);
MainForm.ShowDialog();
this.Close();
So, my question is, how can I pass the data values to the old instance of the main form? without having to create a new instance and show a new instance. Is there a way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为您正在 Form2 代码中创建 Form1 的实例。您想要做的是将 Form2 的 ParentForm 设置为创建它的 Form1 的实例。
此代码只是一个示例,可能无法按原样编译。
This is because you're creating a instance of Form1 in your Form2 code. What you want to do is setup Form2's parentForm to be the instance of the Form1 that created it.
This code is just an example, probably wont compile as-is.
您可以做的是将
MainForm(Form1)
的引用传递给第二个 Form(Form2)
。然后,不再创建MainForm
,而是再次使用引用来更新文本框
。What you can do is pass the reference of
MainForm(Form1)
tosecond Form(Form2)
. Then instead of creatingMainForm
again use the reference to update thetextbox
.主窗体:
子窗体:
main form:
child form: