0

I'm trying to create two Windows Forms with buttons in order to linking them to each other, using this code:

private void cmdInformation_Click(object sender, EventArgs e)
{
    frmInformation information = new frmInformation();
    information.Show();
}

(It's the same way for the second form) When using this code you will have multiple windows of same form if you keep clicking the buttons. What can I do to stop this?

The best solution will be linking forms together without creating a new one, but I don't know any other way than one above.

Tested Hide() but it just hides the multiple windows and program remain open even if you close last shown window.

Tried Close() but when it close the main form whole program is ended.

farshad
  • 764
  • 10
  • 25
  • 2
    What did you expect? `frmInformation information = new frmInformation();` will create a new `frmInformation` instance every time you click that button. – Transcendental Apr 13 '16 at 11:17
  • You need to disable the button once you have clicked it. That way no more instances can be made. Is this what you need? – Stephen Wilson Apr 13 '16 at 11:21
  • @Transcendental That's exactly my problem, too. I don't know any way to link forms without creating a new one. I there is any that will be my answer. – farshad Apr 13 '16 at 12:15
  • This solved my problem: [how-to-switch-between-forms-without-creating-new-instance-of-forms](http://stackoverflow.com/questions/22369893/how-to-switch-between-forms-without-creating-new-instance-of-forms) – farshad Apr 20 '16 at 11:36

3 Answers3

3

Use a dialog.

information.ShowDialog();

You can also read up on dialog results and get responses from your form if that is needed.

Jacob
  • 371
  • 3
  • 12
1

An option would be to create a FormFactory that keeps track of the instances, this way if the form doesn't exist you can create a new instance and show it. If the form exists you can just show the current instance.

Zalomon
  • 553
  • 4
  • 14
1

Move the creation of the opposing form outside of the click event.

frmInformation information = new frmInformation();

private void cmdInformation_Click(object sender, EventArgs e)
{
    information.Show();
}

This will re-display the same form over and over maintaining any data even when the user closes it.

Brian from state farm
  • 2,825
  • 12
  • 17