[英]Passing one cell of DataGridView form form2 to textbox of in form1
我在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中。
請幫我。
這是一個常見的錯誤:
線
Form1 fr1 = new Form1();
創建一個新的Form1實例,而var fr1不引用顯示的原始Form1。
要解決此類問題,您需要將Form1的原始實例傳遞給Form2的構造函數,將引用保存在全局實例var中,然后在form2中使用該引用。 例如:
呼叫:Form2 fr2 =新的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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.