1

I basically want something that does this:

if (form.isOpen() == true)
    form.ShowDialog();
else
    form f = new form();

I have a form that displays a list of items added to an order, but when I go to another page and navigate back to make an order form it calls form f = new form();, which I believe resets the form. Any suggestions of how this can be overcome?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
user5467760
  • 69
  • 1
  • 7

4 Answers4

2

You can check which forms are open using Application.OpenForms property as follows:

if (Application.OpenForms.OfType<MyForm>().Any())
{
    Application.OpenForms.OfType<MyForm>().First().BringToFront();
}
else
{
    form f = new MyForm();
    f.show();
}
The_Black_Smurf
  • 5,178
  • 14
  • 52
  • 78
  • This works well, and you don't need to use `showDialogue` and make the form modal. Of course, you can only have *one* instance of that form. – bgmCoder Feb 27 '20 at 02:12
1

Use the static property Application.OpenForms

YourFormType f = Application.OpenForms.OfType<YourFormType>().FirstOrDefault();
if (f != null)
    f.ShowDialog();
else
{
    using(f = new YourFormType())
    {
        f.ShowDialog();
    }
}

However I don't know if this is going to solve your problem. You might be better off separating your form from it's backing data and using binding to connect the two. When you navigate back you just pass the backing data to the new copy of the form. Look in to concepts like MVVM for more information.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
0

If you call ShowDialog() you can't go to another form within same application (until you have multiple UI threads). If you meant Show() instead of ShowDialog i'd say you just have a

     Form _form;

in your class and add some guarding code, like that (generic idea, though):

     void ShowOrCreate()
     {
        if(_form==null)
        {
            _form = new MyForm();
            _form.Closed += OnMyFormClosed();
            _form.Show();
        }
        else
        {
            _form.BringToFront();
        }
      }

      void OnMyFormClosed(...)
      {
         _form = null;
      }

sorry for missing parts and method signatures, I am sure the can be easily checked in MSDN.

Alex Seleznyov
  • 905
  • 6
  • 18
0

A kind of singleton assuming you want single instance of given form per application:

public MyForm: Form
{
    private static MyForm _instance;

    public static MyForm Instance
    {
        get
        {
            if(_instance == null)
                _instance = new MyForm();
            return instance;
        }
    }
}

Now you can simply use MyForm.Instance. Note, with this approach you don't want to call MyForm.Instance.Close() ever (or you have to re-create instance). Use either Show/Hide (modeless) or ShowDialog/Hide (modal).

Sinatr
  • 20,892
  • 15
  • 90
  • 319