如何在Form1、WinForms C#中使用Form2的一个变量? [英] How to use a variable of Form2 in Form1, WinForms C#?
问题描述
我在 Visual Studio 2013 中有一个解决方案,其中包含两个表单.我希望当在 Form2 中按下按钮时,变量 flag_fb
被更新并且我在 Form1 中使用它的值.有没有办法做到这一点?谢谢.
I have a solution in Visual Studio 2013 which contains two Forms. I want when a button pressing in Form2, the variable flag_fb
is updated and I use its value in Form1. Is there any way to do this? Thanks.
推荐答案
Method1 : 使用参数化构造函数在表单之间传递变量
Method1 : using parameterized constructor to pass the variables between forms
为 Form1
创建一个参数化构造函数,并从 Form2 调用 Form1 参数化构造函数:
create a parameterized constructor for Form1
and call the Form1 parameterized constructor from Form2 :
//form1 code
bool flag_fb =false;
public Form(bool flag_fb)
{
this.flag_fb = flag_fb;
}
从 Form2
调用 Form1
参数化构造函数,如下所示:
call the Form1
parameterized constructor from Form2
as below:
//form2 code
Form1 form1=new Form1(flag_fb);
from1.Show();
Method2 : 在 Form2
中创建变量 flag_fb
作为 public static
变量,以便它可以从 Form1
也是.
Method2 : create your variable flag_fb
as public static
variable in Form2
so that it willbe accessible from Form1
aswell.
//Form2 code
public static bool flag_fb = true;
要从 Form1
访问 flag_fb 变量
,只需使用 className 如下:
To access the flag_fb variable
from Form1
just use className as below:
//Form1 code
bool form2flagValue = Form2.flag_fb ;
这篇关于如何在Form1、WinForms C#中使用Form2的一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!