如何将变量的值从第二种形式传递到第一种形式?

时间:2011-01-20 04:15:28

标签: c# winforms

在C#中,假设有两种形式:第一种和第二种。第一种形式是程序通过使用开始的,它基本上是与其他形式相关的霸主。第二种形式是特定用途的东西,当在第一个表单上单击某个按钮时,它会以模态方式产生(正确的单词?)。所有第二种形式都是从用户那里获得选择。它可以很容易地表示为int或string。现在当第二个表单关闭时(当用户点击该表单上的唯一按钮以锁定他们的选择时),存在关于该变量的小问题,该变量存储了选择丢失而没有被复制到第一个表单。我该如何缓解这个问题?我更希望变量实际上只在第一种形式的类中,而不是第二种形式的类,除非这会导致超过几行额外的代码。

3 个答案:

答案 0 :(得分:1)

表单是类。他们可以拥有公共财产。让第一个表单创建第二个表单,然后使用变量的值设置一个属性。然后第二种形式可以使用该属性。

答案 1 :(得分:1)

两种形式。 Form1和Form2。 Form2以模态方式生成,使用ShowWindow(this),此参数确保Form2只有Form1生成它,因此在这种情况下,它设置内部属性(简称)。作为一个加号,属性是declarerd internal,用于一个程序集,并且只能由Form2写入。

达到预期结果的最佳方式就是这样。

Form1中:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace test1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //declate private varliables
        int parameter1;
        string parameter2;

        private void button1_Click(object sender, EventArgs e)
        {
            // create form
            Form2 form2 = new Form2();
            if (form2.ShowDialog(this) == DialogResult.OK)
            {
                // if the button is pressed
                parameter1 = form2.Parameter1;
                parameter2 = form2.Parameter2;
            }        
        }
    }
}

窗体2:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace test1
{
    public partial class Form2 : Form
    {        
        public Form2()
        {
            InitializeComponent();
        }

        //declate internal parameters
        internal int Parameter1 { get; private set; }
        internal string Parameter2 { get; private set; }

        private void button1_Click(object sender, EventArgs e)
        {
            // if the button is pressed
            Form1 form1 = this.Owner as Form1;
            if (form1 != null) 
            {
                // sets the local parameters
                Parameter1 = -1;
                Parameter2 = "John Doe";

                this.DialogResult = DialogResult.OK;

                Close();
            }
        }
    }
}

答案 2 :(得分:0)

如果我理解正确,那么您希望从FORM2更新FORM1值,以便您可以使用以下任一方式Parent Form()或Delegate进行更新。

要使用父表单,您需要类似的内容,

           (ParentForm as Form1).MyProperty = 123;
           //This will work if you working in MDI like scenario.

我建议使用委托。