-1

I'm quite new to C#. I'm using VS 2010.

What is the easiest way to pass many variables from form1 to form2? I have a class that contains over 10 variables but I don't know how to pass them at one time.

Maybe there is a better way to do that?

Rodrigo Taboada
  • 2,727
  • 4
  • 24
  • 27

4 Answers4

2

Refactor your variables to a class with properties. Create an instance of this class and pass this around where needed

Sievajet
  • 3,443
  • 2
  • 18
  • 22
  • The correct/best answer is this one here. Have a class which contains the needed properties to be passed around - cleaner code and everything is self contained. – Ahmed ilyas Feb 14 '15 at 16:23
0

First of all you should provide more details regarding your demands for example: if the other form should be able to change the data and these changes would be reflected in the first form, are these two forms running in the same appdomain and ect..

There are many ways to do it here are just some from the back of my mind:

  1. An easy way could be, have your class implement an an interface exposing the data, and pass it to the other form in the constructor( getters + setters \ only getters depends on the logic)

  2. Create a simple dto(Data Transfer Object) and pass it to the other form.

  3. Use shared memory mapping.

  4. Middle way point service ..

  5. Sockets\ sychroniztion context

  6. DataBase ...

Roman Ambinder
  • 369
  • 3
  • 7
0

It's easy declare all your variables as private, and then assign getters and setters, example Form1:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private string var1;
        private string var2;

        public string Var1{get{return this.var1;}set{this.var1 = value;}}    
        public string Var2{get{return this.var2;}set{this.var2 = value;}}              

        public Form1()
        {
            InitializeComponent();
        }  
    }
}

Then you can get or set your variables from Form2, example:

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();

            Form1 frm = new Form1();

            frm.Var1 = "Mystring1";
            frm.Var2 = "Mystring2";

            MessageBox.Show(frm.Var1);
            MessageBox.Show(frm.Var2);
        }
    }
}
Dn24Z
  • 149
  • 5
  • This is the recommended way link: http://stackoverflow.com/questions/1568091/why-use-getters-and-setters – Dn24Z Feb 14 '15 at 17:37
-2

Put public in front of all your variables. Then, when setting up form2, you would usually get text in the main code window saying public class Form2 : Form. Replace this with public class Form2 : Form1 so that it adopts all of the properties of Form1.

Sophie Coyne
  • 1,018
  • 7
  • 16