How to use a variable of Form2 in Form1, WinForms

2019-03-05 14:53发布

问题:

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.

回答1:

Method1 : using parameterized constructor to pass the variables between forms

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;
}

call the Form1 parameterized constructor from Form2 as below:

//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.

//Form2 code

public static bool flag_fb = true;

To access the flag_fb variable from Form1 just use className as below:

//Form1 code

bool form2flagValue = Form2.flag_fb ;


回答2:

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.