从Form2中的值更新Form1中的变量

时间:2013-04-02 03:43:55

标签: c# winforms visual-studio-2010 textbox

我有2个表单,名字是HomeForm,第二个名字是cfgForm

我有变量,在HomeForm中命名为strCNF,在cfgForm中为变量CNF命名为strCNF。

这里是HomeForm的代码:

private void cnfRulesMenu_Click(object sender, EventArgs e)
{
    try
    {
        cfgForm cfgForm = new cfgForm(this);
        cfgForm.Show();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString(), "Error");
    }
}

// other parts....
public cfgForm cfg;
string strCNF = "";
strCNF = ((cfgForm)this.cfg).CNF;

然后,在cfgForm的另一种形式中,这里是代码:

public string CNF = "S -> NP VP" + System.Environment.NewLine +
                        "NP -> DT NN | QT NN | NP PP | NP RC | n | p" + System.Environment.NewLine +
                        "DT -> d" + System.Environment.NewLine +
                        "NN -> JJ NN | n" + System.Environment.NewLine +
                        "JJ -> JJ JJ | j" + System.Environment.NewLine +
                        "QT -> q" + System.Environment.NewLine +
                        "PP -> PT NP | GG PP" + System.Environment.NewLine +
                        "PT -> i" + System.Environment.NewLine +
                        "GG -> g" + System.Environment.NewLine +
                        "RC -> WH NP | WH VP" + System.Environment.NewLine +
                        "WH -> w" + System.Environment.NewLine;

    public cfgForm(HomeForm homeForm)
    {
        // TODO: Complete member initialization
        InitializeComponent();
        this.homeForm = homeForm;
    }

    private void btnDefaultCFG_Click(object sender, EventArgs e)
    {
        tbCNF.Text = CNF;
    }

    private void cfgForm_Load(object sender, EventArgs e)
    {
        tbCNF.Text = CNF;
        btnApplyCNF.Enabled = false;
    }

    private void btnApplyCNF_Click(object sender, EventArgs e)
    {
        //CNF = "";
        CNF = tbCNF.Text;
        HomeForm homeForm = new HomeForm();
        homeForm.cfg = this;
        //homeForm.ShowDialog(); 
        this.Hide();// doesn't work
    }

到目前为止,那些代码运行良好,如果我使用homeForm.ShowDialog()。 我的意思是,在cnfRulesMenu_Click处于活动状态并且显示cfgForm支持HomeForm之后,我更新cfgForm中的CNF变量,然后返回HomeForm和cfgForm.Hide。但它给出了零值。

任何建议先生......

1 个答案:

答案 0 :(得分:1)

因为您在这些代码中新增了另一个HomeForm

private void btnApplyCNF_Click(object sender, EventArgs e)
{
    //CNF = "";
    CNF = tbCNF.Text;
    HomeForm homeForm = new HomeForm();
    homeForm.cfg = this;
    //homeForm.ShowDialog(); 
    this.Hide();// doesn't work
}

因此,这些代码无法按您的意愿运作。

public cfgForm cfg;
string strCNF = "";
strCNF = ((cfgForm)this.cfg).CNF;

将代码修改为可能会解决您的问题,但我必须说这些架构没有意义。

private void btnApplyCNF_Click(object sender, EventArgs e)
{
    //CNF = "";
    CNF = tbCNF.Text;
    this.homeForm.cfg = this;
    //homeForm.ShowDialog(); 
    this.Hide();// doesn't work
}