C# – 两种表单之间的数据传输

我有两种forms。 第一个有一个文本框。第二个有一个devexpress数据网格。 我想实现这一点:首先单击一个按钮,然后打开form2。 如果我在form2中的数据网格中单击一行,则该值应显示在form1中的文本框内。(form1已经打开。)mama beginner。 谢谢你的帮助。

Form1 frm1 = new Form1(); frm1.textBox1.Text = gridView1.GetFocusedRowCellValue("ID").ToString(); frm1.Show(); 

当我这样做时,会打开一个新表格。 我不想打开一个新表格。 Form1已经打开。 我想在其文本框中添加值。

将form1作为对form2的引用:

在表单1上的按钮单击处理程序中打开表单2

 private void Button_Click(object sender, EventArgs e) { Form2 frm2 = new Form2(this); frm2.Show(); } 

form2代码

 private Form1 frm1; // constructor (pass frm1 as reference) public Form2(Form1 frm1) { this.frm1 = frm1; } //put this in your event handler for a row click in the grid frm1.textBox1.Text = gridView1.GetFocusedRowCellValue("ID").ToString(); 

你可以尝试这样的事情。

当你单击frm1.SimpleButton时,这个函数将被称为show your Form2。 在Form2上,您必须设置InnerProperty(来自您的数据网格?)a当您关闭Form2时,您可以使用此属性。

 private void SimpleButton_Click(object sender, EventArgs e) { using (Form2 frm = new Form2()) { frm.InnerProperty = "default text"; DialogResult result = frm.ShowDialog(); SimpleButton.Text = frm.InnerProperty; } } 

最后,我解决了这个问题。

 Application.OpenForms["form1"].Controls["textBox1"].Text = gridView1.GetFocusedRowCellValue("ID").ToString(); 

感谢帮助。