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

后端 未结 2 413
醉酒成梦
醉酒成梦 2021-01-28 11:24

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 For

相关标签:
2条回答
  • 2021-01-28 11:42

    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.

    0 讨论(0)
  • 2021-01-28 11:52

    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 ;
    
    0 讨论(0)
提交回复
热议问题