AzgarD
AzgarD

Reputation: 27

Opening child form makes that the UI controls get reset

I am a beginner at windows forms, and I am having some issues with opening child forms.

My application has 2 buttons, one that goes to the main menu, and another that goes to the options.

The problem is that, if I click on a checkbox in the options menu and leave the options tab and come back, the checkbox will not be checked anymore.

This is my code:

private Form CurrentChildForm;

private void OpenChildForm(Form childForm)
{
  if(CurrentChildForm != null)
  {
    CurrentChildForm.Visible = false;
  }
  CurrentChildForm = childForm;
  childForm.TopLevel = false;
  childForm.FormBorderStyle = FormBorderStyle.None;
  childForm.Dock = DockStyle.Fill;
  PanelForForm.Controls.Add(childForm);
  PanelForForm.Tag = childForm;
  childForm.BringToFront();
  childForm.Show();
}

private void MainMenu_Click(object sender, EventArgs e)
{
  OpenChildForm(new MenuForm());
}
private void OptionsMenu_Click(object sender, EventArgs e)
{
  OpenChildForm(new OptionsForm());
}

Upvotes: 0

Views: 78

Answers (1)

Mayer Stefan
Mayer Stefan

Reputation: 36

through your Click-Events on the different buttons you are always creating a new instance of your Forms.

A possible solution is to cache the instance of your optionsMenu for example through a private field, because I consider it being SingleInstance.

private Form CurrentChildForm;
private OptionsForm _opForm;

private void OptionsMenu_Click(object sender, EventArgs e)
{
    if (_opForm == null)
    {
        _opForm = new OptionsForm();
    }

    OpenChildForm(_opForm);
}

Upvotes: 2

Related Questions