0

我的 Form2 上有一个 DataGridView,form1 上有一个文本框。当我单击 DataGridView 行之一时,我想在 form1 的 texboxes 中显示 DataGridView 副本的每个单元格。

我试图将文本框的类型更改为“公共”,然后我在 form2 中写了这个:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex < 0 || e.ColumnIndex < 0)
       return;

    Form1 fr1 = new Form1();
    fr1.textBox1.Text = "123";  
    Form2.ActiveForm.Close();
}

但在 form1 的 texbox1 中没有复制任何内容。

请帮我。

4

1 回答 1

1

这是一个常见的错误:

线

Form1 fr1 = new Form1(); 

创建 Form1 的新实例,并且 var fr1 不引用显示的原始 Form1。
要解决此类问题,您需要将 Form1 的原始实例传递给 Form2 的构造函数,将引用保存在全局实例 var 中并在 form2 中使用该引用。例如:

调用:Form2 fr2 = new Form2(this)

FORM2 构造函数:

public class Form2 : Form
{
     private Form1 _caller = null;

     public Form2(Form1 f1)
     { 
         _caller = f1;
     }
}

DATAGRIDVIEW_CELLCLICK

private void dataGridView1_CellClick(....)
{
    if (e.RowIndex < 0 || e.ColumnIndex < 0)     
       return;     

    _caller.textBox1.Text = "123";       
    this.Close();
}
于 2012-07-16T07:47:25.007 回答