我的問題是,當我在 datagridview 中選擇一行時,它會打開一個新表單,而不是以前的表單。
這是我的代碼:
按鈕:“Form1”中的“choix de l'article”:f2 呼叫 form2
public partial class A_commande : Form
{
public A_commande()
{
InitializeComponent();
}
private void button12_Click(object sender, EventArgs e)
{
A_fournisseur_article f2 = new A_fournisseur_article();
f2.Show();
}
}
Form2:f1呼叫form1
private void articleDataGridView_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
{
A_commande f1 = new A_commande();
DataGridViewRow row = this.articleDataGridView.Rows[e.RowIndex];
f1.articleComboBox.Text = articleDataGridView.CurrentRow.Cells[0].Value.ToString();
f1.catégorieTextBox.Text = articleDataGridView.CurrentRow.Cells[1].Value.ToString();
this.Hide();
f1.Show();
}
}
表格1
表格2
(我的問題):它不是“form1”,但我得到“新 form1”
非常感謝您的參與。
uj5u.com熱心網友回復:
每次需要訪問現有表單時,您都會創建一個新表單。
這有點像每次上班都買一輛新車,而您應該保留鑰匙并再次使用同一輛車。
因此,您需要更改您的第二個表單以在您創建它時接受對您的第一個表單的參考。然后你使用這個參考。
首先以您的第二種形式執行此操作
public partial class A_fournisseur_article : Form
{
//You need somewhere to store the reference to your first form
private A_commande firstForm = null;
private A_fournisseur_article () //Change this to private
{
InitializeComponent();
}
//create a new public constructor, which acepts the reference
public A_fournisseur_article (A_commande myFirstForm) : this() //make sure it call this() which is the constructor above.
{
//Now we store the reference
this.firstForm = myFirstForm;
}
private void articleDataGridView_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
{
//Remove the line below. We don't want a new one!
//A_commande f1 = new A_commande();
DataGridViewRow row = this.articleDataGridView.Rows[e.RowIndex];
//Now you use your reference from earlier
firstForm?.articleComboBox.Text = articleDataGridView.CurrentRow.Cells[0].Value.ToString();
firstForm?.catégorieTextBox.Text = articleDataGridView.CurrentRow.Cells[1].Value.ToString();
this.Hide();
f1.Show();
}
}
}
現在您需要從第一個表單更改創建和呼叫第二個表單的方式
public partial class A_commande : Form
{
public A_commande()
{
InitializeComponent();
}
private void button12_Click(object sender, EventArgs e)
{
//Here, we now pass a reference to this form (A_commande)
A_fournisseur_article f2 = new A_fournisseur_article(this);
f2.Show();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/431272.html
