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

时间:2015-12-01 02:14:30

标签: c# winforms

我一直在尝试在第二个表单上更改整数值。 我有两种形式。第一个是我的主要形式。它包含我想要改变的整数。第二种形式是我的选择形式。我需要在第二个表单上使用数字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个小时。 这是一个学校项目。对不起代码中的法语单词! (法语学校)

1 个答案:

答案 0 :(得分:2)

当您为第一个表单传递参考创建时:

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;

        }