将DataGridView窗体2的一个单元格传递到窗体1中的文本框



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

我试着把文本框的类型改为"公共",然后我用表格2:写了这篇文章

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中没有复制任何内容。

请帮帮我。

这是一个常见的错误:

线路

Form1 fr1 = new Form1(); 

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

呼叫:Form2 fr2=新的Form2(此)

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();
}

最新更新