如何将数据从表单传递到另一个先前从任何其他表单实例化的表单?

我有三个表单(form1,form2,form3),我的主要表单是form1,从我打开form2获取一些数据,我在form2上有一个更新按钮,它将带我到form3,现在我想要无论用户在form3上写什么更新到form2,我怎样才能使用c#.net?

(我使用showdialog()方法打开form2,form3)

//reference to form2 Form2 SecondaryForm = new Form2(mainForm);
SecondaryForm.ShowDialog(); //in the constructor of Form2 save the reference of Form1 Form1 form1 = null Form2(Form1 mainForm) { form1 = mainForm; } //then instead of creating a new MainForm again just use reference of Form1 form1.updateText(data); this.Close()

我使用了上面的代码但是我在form1.updateText(data)上得到了nullreferenceexception;

只需将表单2引用传递给表单3,同时实例化它。就像在打开form2时对form1所做的那样。 然后从form3使用form2引用调用updatetext方法,该方法应该是form2上的公共方法

这里是所有3个表单的代码,您可以从其他表单更新任何表单,我已经创建它,以便您可以访问form3中的form1和form2。

 using System; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form2 frm2; public Form3 frm3; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } public void updateText() { this.textBox1.Text = ""; } private void button1_Click(object sender, EventArgs e) { if (frm2 == null) frm2 = new Form2(this); frm2.ShowDialog(); } } } using System; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form2 : Form { public Form1 refToForm1; public Form2(Form1 f1) { refToForm1 = f1; InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (refToForm1.frm3 == null) refToForm1.frm3 = new Form3(this); refToForm1.frm3.ShowDialog(); } public void UpdateForm2(string txt) { this.textBox1.Text = txt; } } } using System; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form3 : Form { Form2 refToForm2; public Form3( Form2 f2) { refToForm2 = f2; InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //Pass any data to Form1; refToForm2.refToForm1.updateText(); //Pass data to form2 refToForm2.UpdateForm2("from form3"); } } } 

我试过这个。 我创建了两个表单,每个表单都有一个buttontextbox 。 在Form1

  public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { Form2 SecondaryForm = new Form2(this); SecondaryForm.ShowDialog(); } public void updateText(string txt) { textBox1.Text = txt; } 

然后在Form2

  Form1 form1 = null; public Form2(Form1 mainForm) { form1 = mainForm; InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { form1.updateText(textBox1.Text); this.Close(); } 

我使用了它并且它起作用,我没有例外

虽然它可能不适合您的数据,但您可以将表单视为代表所有数据的基础“模型”的“视图”吗? 如果是这样,您可以创建“模型”类的实例,并为所有3个表单提供参考。 有关“查看”和“模型”的一些说明,请参见此处 。