locked
Passing Variables between Forms RRS feed

  • Question

  • Hi

    I have two forms: form1 and form2.

    In form1, I have a Variable Variable1, say, int.

    How can I access the value of variable1 in form2?

    Thanks


    New Ideas, Superior Solutions Www.SalamGroup.Net
    Tuesday, March 15, 2011 6:26 PM

Answers

  • Just declare your variable as static and int globally in your Form1 and access it in 2nd form. e.g

    public static int variable1;
    // declaration in form1
    
    Form1.variable1 = 10;
    // changing value of variable1 in Form2
    
    int temp = Form1.variable1;
    //accessing value of variable1 in form2
    

    If you just want your user to

    1. access the value not to change its value from form2

    or

    2. just want to change the value in form2 but can't be assigned to any other variable in form2

    then use the following code

        private static int _variable1;
        public static int variable1
        {
          get // this makes you to access value in form2
          {
            return _variable1;
          }
          set // this makes you to change value in form2
          {
            _variable1 = value;
          }
        }
    // this code is in form1 and must be declared globally 
    // You can access or change value in form2 using the code described in upper example.
    
    Just remove "set" block if you want 1st option or remove "get" block if you want 2nd option. Otherwise use both block which makes user to access as well as change value in form2


    How To Articles
    • Marked as answer by Engineer Mahdi Wednesday, March 16, 2011 2:58 AM
    Tuesday, March 15, 2011 7:36 PM

All replies

  • There are like 20+ forums with the answer to this question.  Pls see below for your answer:

    http://social.msdn.microsoft.com/Forums/en-US/vblanguage/thread/f70d637b-9490-405c-8553-06f46817abdd/

    Tuesday, March 15, 2011 6:32 PM
  • Just declare your variable as static and int globally in your Form1 and access it in 2nd form. e.g

    public static int variable1;
    // declaration in form1
    
    Form1.variable1 = 10;
    // changing value of variable1 in Form2
    
    int temp = Form1.variable1;
    //accessing value of variable1 in form2
    

    If you just want your user to

    1. access the value not to change its value from form2

    or

    2. just want to change the value in form2 but can't be assigned to any other variable in form2

    then use the following code

        private static int _variable1;
        public static int variable1
        {
          get // this makes you to access value in form2
          {
            return _variable1;
          }
          set // this makes you to change value in form2
          {
            _variable1 = value;
          }
        }
    // this code is in form1 and must be declared globally 
    // You can access or change value in form2 using the code described in upper example.
    
    Just remove "set" block if you want 1st option or remove "get" block if you want 2nd option. Otherwise use both block which makes user to access as well as change value in form2


    How To Articles
    • Marked as answer by Engineer Mahdi Wednesday, March 16, 2011 2:58 AM
    Tuesday, March 15, 2011 7:36 PM
  • //form1:
    public int Variable1 { get; private set; }
    
    private void YourmethodToSetVariable()
    {
     Variable1 = 22:
    }
    
    private void OpenForm2()
    {
      Form2 f2 = new Form2(this);
      f.Show();
    }
    
    //form2:
    Form1 f1:
    public Form2(_Form1 _f1)
    {
      //constructor of Form2
      InitializeComponent();
      this.f1 = _f1;
    }
    
    private void AccessToVariableOnForm1()
    {
      //here you access to the variable on form1:
      int Variable2 = f1.Variable1;
    }
    

    Hope it helps,

    mitja

    Tuesday, March 15, 2011 7:56 PM
  • It is not "wise" to pass forms around. Always use events when passing data from sibling forms back to the "main" form

    Passing Values between Forms   

    Now Form2 knows everything about Form1.

    Forms shouldn't be coupled together like this. Form2 shouldn't have knowledge of Form1. This requires the instantiatee to have knowledge of the instantiator.  The only knowledge it should have is that form2 will create an event that form1 will subscribe to in order to purpose the form's text or whatever control appropriately.

    As JohnWein has told me once on occasion when I presented that years ago, "As Form1, I don't want to give you a key to my house.  When you're done with each task call me and leave a message on my answering machine.  Tell me what task you have completed and I'll take it from there.  Since you are passing an object, you only need 1 delegate and 1 event.  The number of methods on each form to handle the passing of information is up to each form's author. "


    John Grove, MCC - Senior Software Engineer
    Tuesday, March 15, 2011 8:08 PM
  • Here is an example:

    Form1

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication1
    {
      public partial class Form1 : Form
      {
        private Form2 Frm2 = new Form2();
    
        public Form1()
        {
          InitializeComponent();
          Frm2.AdviseParent += new Form2.AdviseParentEventHandler(SetFromForm2);
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
          Frm2.ShowDialog();
        }
    
    
        public void SetFromForm2(string label)
        {
          label1.Text = label;
        }
    
      }
    }
    
    

    //Form2

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication1
    {
      public partial class Form2 : Form
      {
        public delegate void AdviseParentEventHandler(string text);
        public event AdviseParentEventHandler AdviseParent;
    
        public Form2()
        {
          InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
          SetLabelOnForm1(textBox1.Text);
        }
    
        public void SetLabelOnForm1(string label)
        {
          if (AdviseParent != null)
            AdviseParent(label);
        }
      }
    }
    

     

     


    John Grove, MCC - Senior Software Engineer
    • Proposed as answer by Agalo Wednesday, March 16, 2011 5:01 AM
    • Unproposed as answer by Agalo Wednesday, March 16, 2011 5:01 AM
    Tuesday, March 15, 2011 8:16 PM
  • Or the "proper way" is this:

    Form1

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    
    namespace GenericEvent
    {
      public partial class Form1 : Form
      {
        public Form1()
        {
          InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
          Form2 frm2 = new Form2();
          frm2.AdviseParent += new EventHandler<AdviseParentEventArgs>(frm2_AdviseParent);
          frm2.Show();
        }
    
        private void frm2_AdviseParent(object sender, AdviseParentEventArgs e)
        {
          label1.Text = e.AdviseText;
        }
    
        
      }
    }
    
    Form2

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    
    namespace GenericEvent
    {
      public partial class Form2 : Form
      {
        public event EventHandler<AdviseParentEventArgs> AdviseParent;
    
        public Form2()
        {
          InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
          OneSetLabel(textBox1.Text);
        }
    
        protected virtual void OneSetLabel(string text)
        {
          EventHandler<AdviseParentEventArgs> handler = AdviseParent;
          if (handler != null)
          {
            AdviseParentEventArgs e = new AdviseParentEventArgs(textBox1.Text);
            handler(this, e);
          }
        }
      }
    
      public class AdviseParentEventArgs : EventArgs
      {
        private readonly string adviseText;
    
        public AdviseParentEventArgs(string adviseText)
        {
          this.adviseText = adviseText;
        }
    
        public string AdviseText
        {
          get { return adviseText; }
        }
      }
    }
    

     

     


    John Grove, MCC - Senior Software Engineer
    • Proposed as answer by Agalo Wednesday, March 16, 2011 5:01 AM
    Tuesday, March 15, 2011 8:18 PM
  • Look also here:

    http://social.msdn.microsoft.com/Forums/eu/csharpgeneral/thread/cbe7e1cf-21ac-44ab-be3f-71f85c95bc38

     

    Noam B.



    Do not Forget to Vote as Answer/Helpful, please. It encourages us to help you...
    • Proposed as answer by Noam B Wednesday, March 16, 2011 6:30 AM
    Wednesday, March 16, 2011 6:29 AM
  • Using "static" variables as a means to pass things across forms is not the way to do things. I can't believe that is marked as the answer. I mean no offense to the answerer who posed it, but it is not the way object oriented programming is done and it is certainly not good practice. Programmers should get in the habit of caring about their code and doing things right.
    John Grove, MCC - Senior Software Engineer
    Thursday, March 17, 2011 3:09 PM
  • //In Form2 , create a function as Public

    string strQuery = "";
            string rpt = "";

      public void LoadWindow( string _strQuery, string _rpt)

            {
                strQuery = _strQuery;
                rpt = _rpt;
            }

    //in form1, create object for form2

    string str1="parameter1";

    string str2="parameter2";

    frmForm2 obj=new frmForm2();

    obj.LoadWindow(str1,str2);

    obj.Show();

    • Proposed as answer by SivaSree Thursday, January 10, 2013 10:15 AM
    Wednesday, January 9, 2013 5:10 AM
  • Thanks. Very use full

    Wednesday, December 25, 2013 4:08 PM
  •         public Form2(string variable1,string variable2)
            {
                InitializeComponent();
                this.Text = variable1;
                label1.Text = variable2;
            }

    Full Source : Passing Values Between Forms

    Bona

    Tuesday, July 1, 2014 5:48 AM
  • a very easy way

    //in form 1
    
    public void setvar(int v)
    {
       varrible1=v;          
    }                        
    
    public void getvar(int v)
    {
       v=varrible1;
       return v;
    }
    
    
    //in form 2
    
    int varrible;
    
    form1 myform = new form1;
    
    myform.setvar(varrible);  
                              
    
    
    myform.getvar(varrible); 
    


    Tuesday, November 4, 2014 6:47 PM
  • I don't think it is necessary to be constrained by the EventHandler class; a delegate can be used that is defined in whatever way is most appropriate.



    Sam Hobbs
    SimpleSamples.Info

    Tuesday, February 13, 2018 9:58 PM