Transferring an object to different forms of windows

I want to pass a C # object between win forms. At the moment, I have set up a basic project to learn how to do this, which consists of two forms - form1 and form2 and a class with class class1.cs, which contains get and set methods for setting a string variable with the value entered in form1. (Form 2 should get the value stored in class1 object)

How to get a string value from an object that was set to form1? Do I need to pass it as a parameter in form2?

Any comments / help will be voiced!

Thank,

EDIT: Here is the code that 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);
        }
    }
}

}

+5
source share
3 answers

, , .

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

,

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

, , Form1, Form2 .

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

Form2, .

public Class1 MyClass {get;set;}

Class1 , 2.

+8

, Form1 1, , Form2. , Form2 Class1. , Form1 Form2, Form1 Form2 .

+4

ASP.Net , Newtonsoft.Json. , WinForms, , , ... - !

:

// Set Object Property within Form
 public partial class FlashNotify : Form
 {
     public string Json { get; set; }
 }

:

 private void FlashNotify_Load(object sender, EventArgs e)
 { 
    // Deserialize from string back to object
    CommUserGroupMessage msg = new CommUserGroupMessage();
    msg = Newtonsoft.Json.JsonConvert.DeserializeObject<CommUserGroupMessage>(Json);
 }

, :

// Serialize the Object into a string to pass
 string json = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
 FlashNotify fn = new FlashNotify();
 fn.Json = json;
 fn.Show();

, , , as this eliminates the need to duplicate a class in your form, which I think makes it easier to maintain( Bugfix: Miss read the static class correctly in the example, I thought at first that it was reproduced inside the form).

0
source

All Articles