将DataGridView表单的一个单元格传递给form1中的文本框

时间:2012-07-16 07:43:12

标签: c# visual-studio-2010

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

我尝试将文本框的类型更改为“public”,然后我在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中复制。

请帮助我。

1 个答案:

答案 0 :(得分:1)

这是一个常见的错误:

Form1 fr1 = new Form1(); 

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

CALLING:     Form2 fr2 = new Form2(this)

FORM2 CONSTRUCTOR:

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();
}
相关问题