Passing object to different windows forms

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.

public static class MyStaticClass
{
  public static string MyStringMessage {get;set;}
}

You don't need to instance the class, just call it

MyStaticClass.MyStringMessage = "Hello World";
Console.WriteLine (MyStaticClass.MyStringMessage);

If you want an instance of the object you can pass the class object that you create on Form1 into Form2 with the following.

private void button1_Click(object sender, EventArgs e)
    {
        this.Hide();
        Form2 form2 = new Form2();
        form2.MyClass = class1;
        form2.Show();
    }

Then create a property on Form2 to accept the class object.

public Class1 MyClass {get;set;}

remember to make the Class1 object a global variable rather than create it within button 2 itself.


Yes, in Form1 you declare an instance of Class1 and then set the parameters as needed, then you pass it to Form2. You could for example have a constructor in Form2 and have a Class1 parameter in it. Assuming that Form1 creates Form2, otherwise you have to have some way for Form1 to find Form2 to pass the instance across.

Tags:

C#

Winforms