从Form2中的值更新Form1中的变量
本文关键字:Form1 变量 更新 Form2 | 更新日期: 2023-09-27 18:06:51
我有两个表单,第一个名为HomeForm,第二个名为cfgForm
我有变量,名称strCNF在HomeForm, strCNF的值从变量CNF在cfgForm。
下面是来自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,然后我更新CNF变量在cfgForm,然后回到HomeForm,和cfgForm. hide。但是它给空值
有什么建议吗?
因为你在这些代码中添加了另一个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
}