Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing object to different windows forms

Tags:

c#

winforms

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);
        }
    }
}

}

like image 725
Theomax Avatar asked Jun 02 '10 11:06

Theomax


People also ask

Are Windows Forms cross platform?

It is released under the MIT License. With this release, Windows Forms has become available for projects targeting the . NET Core framework. However, the framework is still available only on the Windows platform, and Mono's incomplete implementation of Windows Forms remains the only cross-platform implementation.


1 Answers

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.

like image 173
Paul Talbot Avatar answered Sep 19 '22 10:09

Paul Talbot