[Solved] C# – How to save a string entered in Form2 in Form1


Look at your ConfigForm. Here’s your problem:

public ConfigForm()
{
    InitializeComponent();
    Form1 frm1 = new Form1();
    frm1.NewPath = NewPathBox.Text;
}

What you’re doing on your Form1 (which I’m guessing is your Main form) is creating a new instance of your ConfigForm and showing it. What you’re doing in your ConfigForm is creating a new main form and setting the NewPath = to the value entered on your config form. The problem is this new Form1 is NOT the Form1 that created the ConfigForm. The Form1 that created your config form is not the one getting updated by your code, some arbitrary new Form1 that you create is the one getting updated. This is why your code isn’t working as you expected.

Here’s the approach I would take. Add a NewPath variable to your ConfigForm just like you have in Form1. Then, add a FormClosing method to FormConfig. Do something like this:

private void ConfigForm_FormClosing(object sender, FormClosingEventArgs e)
{
     NewPath = NewPathBox.Text;
}

Then, change your code on Form1 to this:

private void button1_Click(object sender, EventArgs e)
{
    ConfigForm cfgfrm = new ConfigForm();
    cfgfrm.ShowDialog();
    this.NewPath = cfgfrm.NewPath;
}

What this code is doing is creating and showing a new ConfigForm on your Form1 when you click button1. Then, when your user closes the FormConfig, the form saves the textbox value to the NewPath variable on the FormConfig. Then, once the form is closed, the code on Form1 resumes. Form1 then looks at the NewPath value that was saved when the user closed the FormConfig. Form1 grabs this new NewPath value and puts it in its own NewPath variable.

EDIT

To show/hide comboboxes:

private void button1_Click(object sender, EventArgs e)
{
    ConfigForm cfgfrm = new ConfigForm();
    cfgfrm.ShowDialog();
    this.NewPath = cfgfrm.NewPath;
    Gamedropdown.Visible = false; 
    NewDropDown.Visible = true
}

7

solved C# – How to save a string entered in Form2 in Form1