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?
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?
Refactor your variables to a class with properties. Create an instance of this class and pass this around where needed
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:
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)
Create a simple dto(Data Transfer Object) and pass it to the other form.
Use shared memory mapping.
Middle way point service ..
Sockets\ sychroniztion context
DataBase ...
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);
}
}
}
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.