简体   繁体   中英

How to use a variable of Form2 in Form1, WinForms C#?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM