从表单1的DataGridView到表单2的文本框中获取行数据,而无需再次打开表单2

本文关键字:表单 数据 获取 DataGridView 文本 | 更新日期: 2023-09-27 17:52:16

我有两种形式,form1(包含Textbox)和form2(包含DataGridView和按钮)。现在,我想将form2中的一个选定行数据传递给form1。但问题是,我不想再打开form1。当我点击按钮时,它只会更新文本框

从表单1的DataGridView到表单2的文本框中获取行数据,而无需再次打开表单2

在Form2中声明一个字符串值并将dataGridView的值从dataGridView的CellEnter事件传递给它:

private void dataGridView2_CellEnter(object sender, DataGridViewCellEventArgs e) { sText = dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); }

在Form1中创建一个公共方法来检索和显示这些数据:

public void GetAndDisplay(string sText) { textBox1.Text = sText; } 你需要在Form2中添加一个属性,将Form1定义为Form2的父元素:

public Form1 fParent {get; set;}

然后当从Form1调用它时,你必须这样做:

Form2 f2 = new Form2(); f2.fParent = this; f2.Show();

最后,从Form2的按钮中调用GetAndDisplay方法:

fParent.GetAndDisplay(sText);