Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

c# - Passing object to different windows forms

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

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...