Form2值退出时返回0
本文关键字:返回 退出 Form2 | 更新日期: 2023-09-27 18:13:28
我有主要形式和形式2(这是一个模态形式)。
当我进入FORM 2时,有一个组合框,所选的值将存储在一个类中。从这里开始,它可以正常工作,因为消息框确认该值已被存储。
但是当我退出FORM 2并返回到主表单以在文本框中显示该值时,该值现在返回0。
形式2:
private void btnOK_BS__Spec_Click(object sender, EventArgs e)
{
BSIT bsit = new BSIT();
string spec = cboIT_Spec.Text;
do
{
if (spec == "Animation and Game Development" || spec == "Digital Arts")
{
bsit.setSpec(spec);
MessageBox.Show("You chose " + bsit.getSpec() + ".", "Specialization",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Please select your Specialization.");
}
}
while (bsit.getSpec() == "");
}
类
public class BSIT : Student
{
public BSIT()
{
spec = "";
}
private string spec;
public void setSpec(string spec)
{
if (spec == "Animation and Game Development" || spec == "Digital Arts")
{
this.spec = spec;
}
}
public string getSpec()
{
return spec;
}
}
主表单(显示spec的值)
private void txbxSpec_Input_TextChanged(object sender, EventArgs e)
{
BSIT bsit = new BSIT();
if (!(bsit.getSpec() == ""))
{
txbxSpec_Input.Text = bsit.getSpec();
}
}
您有两个独立的BSIT
类实例。您需要将第一个实例传递到FORM 2的实例中,或者将BSIT类设置为静态。
至少我认为这是原因,从我可以看到你张贴的代码。我不知道你在哪里实例化包含btnOK_BS__Spec_Click
事件的表单。
你在btnOK_BS__Spec_Click
事件中"新建"了一个BSIT
实例,并保存了你的值,但一旦事件结束,它就会超出范围,所以你失去了你的值。然后,您试图从BSIT
的第一个实例中获取用户的值。
你应该在Main表单中发送一个BSIT的新实例,然后将它传递给Form2,这样两个表单就可以访问一个实例,就像这样:
这里我定义了一个构造函数form Form2来给BSIT实例form form main
Public class Form2
{
BSIT result;
public Form2(BSIT bsit)
{
result = bist;
}
...
}
现在,当你在mainform中初始化form2时,你应该有这样的内容:
BIST resultFromForm2 = new BIST();
Form2 frm = new Form2(resultFromForm2);
frm.showDialog();
,你应该有类似的东西在你的按钮点击事件处理程序:(正如你所看到的,我改变了我们之前在构造函数中设置的"result")
private void btnOK_BS__Spec_Click(object sender, EventArgs e)
{
string spec = cboIT_Spec.Text;
do
{
if (spec == "Animation and Game Development" || spec == "Digital Arts")
{
result.setSpec(spec);
MessageBox.Show("You chose " + result.getSpec() + ".", "Specialization",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Please select your Specialization.");
}
}
while (result.getSpec() == "");
}
嗨,你可以参考下面的链接…
将值从一种形式传递到另一种形式
或
http://csharpprobsandsoln.blogspot.in/2013/04/passing-value-from-one-form-to-other.html