I want to pass a C# object between win forms. At the moment, I have setup a basic project to learn how to do this which consists of two forms – form1 and form2 and a class called class1.cs which contains get and set methods to set a string variable with a value entered in form1. (Form 2 is supposed to get the value stored in the class1 object)
How can I get the string value from the object that was set in form1? Do I need to pass it as a parameter to form2?
Any comments/help will be appeciated!
Thanks,
EDIT: Here’s the code I have at the moment: (form1.cs)
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.Show();
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
Class1 class1 = new Class1();
class1.setStringValue(textBox1.Text);
}
}
}
}
There are a few different ways to do this, you could use a static class object, the above example would be ideal for this activity.
You don’t need to instance the class, just call it
If you want an instance of the object you can pass the class object that you create on Form1 into Form2 with the following.
Then create a property on Form2 to accept the class object.
remember to make the Class1 object a global variable rather than create it within button 2 itself.