Search code examples
c#formsreferenceparent

How to take value from form1 to form2 AND back?


Ok so here is the Situation: I want to take a value of a string in form1 to a textbox in form2, edit it and send it back and save it as the string in form1 again. Its that easy but Im too stupid to succed. Yes I googled and tried very long but I just dont seem to find the right tags. I tried it with the following Method:

public partial class form1: Form
{
    public form1()
    {
        InitializeComponent();
    }

    Project.form2 newform2 = new Project.form2();
    string oldtext = "Text here";

    void somefunction()
    {
        oldtext = newform2.getUpdateTxt();
    }
}

and

public partial class form2: Form
{

    Project.form1 newform1 = new Project.form1();
    string UpdateTxt = "";
    public form2()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        UpdateTxt = textBox1.Text;
        this.Hide();
    }

    public string getUpdateTxt()
    {
        return UpdateTxt;
    }

    private void form2_VisibleChanged(object sender, EventArgs e)
    {
         textbox1.Text = newform1.oldtext.Text;
    }
}

obviously not working. Because it creates an infinityloop. I also tried it by putting the

Project.form newform = new Project.form();

In an own function. Solves the loop but now it resets the values while initializing. Also tried to parent the forms somehow like described here but its not helping. C# - How to make two forms reference each other


Solution

  • The simplest solution I can think of for this is to put the value you want to share across forms in a static property of a static class:

    public static class SharedVariables
    {
        public static string OldText { get; set; }
    }
    

    Then you can set a TextBox.Text to the value of the property with:

    textBox1.Text = SharedVariables.OldText;
    

    And you can assign a new value entered in another TextBox.Text with:

    SharedVariables.OldText = textBox2.Text;
    

    That being said, depending on what the purpose of the forms are, this may not be the best solution.