2

I want to check if an instance of a form is opened and open the existing instance to update a textbox else create a new instance.

After searching I found : How to check if a windows form is already open, and close it if it is?

From the accepted answer I tried

try
{
    foreach (Form fm in Application.OpenForms)
    {
        if (fm is Form2)
        {
            Form2 n1 = (Form2)Application.OpenForms["Form2"];
            n1.textBox1.Text = textBox1.Text;
            break;
        }
        else
        {
            Form2 n1 = new Form2();
            n1.textBox1.Text = textBox1.Text;
            n1.Show();
        }
    }
}
catch (InvalidOperationException)
{
}

Apart from that this code throws an InvalidOperationException (which i am already catching), The code doesn't work because if an instance already exists it still creates a new instance.

What am i doing wrong?

Community
  • 1
  • 1

1 Answers1

0

A better approach would be to filter the OpenForms based on the form type:

var form2collection = Application.OpenForms.OfType<Form2>();

You can then loop over those, or if the collection is empty, open a new form. The advantage is that you aren't relying on the form name, but the actual class definition of the form, which is more reliable.

Additionally, I tend to avoid direct manipulation of controls from other code. I find it more reliable if others call a method, such as

public void setSomeControl(string value)
{
    this.controlName.Text = value;
}

then call

form2collection[0].setSomeControl("new value");

which allows your form to do all the housekeeping and the calling code can ignore those details.

Godeke
  • 16,131
  • 4
  • 62
  • 86
  • Thanks. Your answer gave me a clue to what i needed to do. Should i edit your answer and add the code i used? –  Oct 03 '13 at 21:48
  • 1
    Best to edit the *question* to show your final result. Editing an answer will probably be rejected by mods as "invalid edit - attempt to reply". But I'm sure people would appreciate seeing your final solution! – Godeke Oct 03 '13 at 22:33