C#如何在另一个窗体(windows窗体)上更改int值

本文关键字:窗体 int 另一个 windows | 更新日期: 2023-09-27 18:25:04

我一直在尝试更改第二种形式的整数值。我有两张表格。第一个是我的主形式。它包含我要更改的整数。第二个表单是我的选项表单。我需要在第二个表格上使用数字upDown来更改第一个表单上的整数值。问题是,每次打开第二个窗体时,它都会重置第一个窗体。

以下是我如何在第一个表单上打开第二个表单:

private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
{
    // I need to access the second form
    frmOptions frmOptionsJeux = new frmOptions();
    frmOptionsJeux.Show(); 
}

第二表单代码:

namespace TP3
{
    public partial class frmOptions : Form
    {
        // I need to access the first form
        frmPrincipal frmJeu = new frmPrincipal();

        public frmOptions()
        {
            InitializeComponent();
            // Sets the value of the Numeric UpDowns (boiteNbLignes & boiteNbColonnes
            // nbLignesDansTableauDeJeu & nbColonnesDansTableauDeJeu are the two integers I need to modify.
            boiteNbLignes.Value = frmJeu.nbLignesDansTableauDeJeu;
            boiteNbColonnes.Value = frmJeu.nbColonnesDansTableauDeJeu;
        }
        //The integers are only modified when I click OK
        private void btnOK_Click(object sender, EventArgs e)
        {
            AppliquerOptionsTaille();
            this.Hide();             
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Hide();
        }
        // How the integers are supposed to be modified
        public void AppliquerOptionsTaille( )
        { 
            frmJeu.nbLignesDansTableauDeJeu = (int)boiteNbLignes.Value;
            frmJeu.nbColonnesDansTableauDeJeu = (int)boiteNbColonnes.Value;                  
        }
    }
}

我不知道我做错了什么。我已经试了至少4个小时了。这是一个学校项目。抱歉代码中的法语单词!(法国学校)

C#如何在另一个窗体(windows窗体)上更改int值

创建第二个表单时,将引用传递给第一个表单:

frmOptions frmOptionsJeux = new frmOptions(this);
    frmOptionsJeux.Show(); 

然后在第二种形式的构造函数中将它设置为私有变量:

private Form1 parent
public frmOptions(Form1 formRef)
        {
            InitializeComponent();
            // Sets the value of the Numeric UpDowns (boiteNbLignes & boiteNbColonnes
            // nbLignesDansTableauDeJeu & nbColonnesDansTableauDeJeu are the two integers I need to modify.
            boiteNbLignes.Value = frmJeu.nbLignesDansTableauDeJeu;
            boiteNbColonnes.Value = frmJeu.nbColonnesDansTableauDeJeu;
            parent = formRef;
        }