[英]How to use a variable of Form2 in Form1, WinForms C#?
I have a solution in Visual Studio 2013 which contains two Forms. 我在Visual Studio 2013中有一个解决方案,其中包含两个窗体。 I want when a button pressing in Form2, the variable
flag_fb
is updated and I use its value in Form1. 我想要在Form2中按下按钮时更新变量
flag_fb
,并在Form1中使用其值。 Is there any way to do this? 有什么办法吗? Thanks.
谢谢。
Method1 : using parameterized constructor to pass the variables between forms 方法1:使用参数化的构造函数在窗体之间传递变量
create a parameterized constructor for Form1
and call the Form1 parameterized constructor from Form2 : 为
Form1
创建一个参数化的构造函数,并从Form2调用Form1的参数化构造函数:
//form1 code
bool flag_fb =false;
public Form(bool flag_fb)
{
this.flag_fb = flag_fb;
}
call the Form1
parameterized constructor from Form2
as below: 从
Form2
调用Form1
参数化的构造函数,如下所示:
//form2 code
Form1 form1=new Form1(flag_fb);
from1.Show();
Method2 : create your variable flag_fb
as public static
variable in Form2
so that it willbe accessible from Form1
aswell. 方法2:在
Form2
flag_fb
变量flag_fb
创建为public static
变量,以便也可以从Form1
对其进行访问。
//Form2 code
public static bool flag_fb = true;
To access the flag_fb variable
from Form1
just use className as below: 要从
Form1
访问flag_fb variable
,只需使用className,如下所示:
//Form1 code
bool form2flagValue = Form2.flag_fb ;
Something like this should also work. 这样的事情也应该起作用。
// Open form2 from form1
using (Form2 form2 = new Form2())
{
if (form2.ShowDialog() == DialogResult.OK)
{
m_myVal = form2.flag_fb;
}
}
You should make sure flag_fb
is public member variable of Form2
, and also make sure it is set to desired value when user clicks OK for instance. 您应确保
flag_fb
是Form2
公共成员变量,并确保在用户单击“确定”时将其设置为所需的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.