tags:

views:

40

answers:

2

Let's say I open a form in the following way:

FormSomething FormSomething = new FormSomething(SomethingId);
FormSomething.Show();

In my code, there is a possibility for many FormSomething's to be open at once. How do I close a specific instance of a FormSomething?

Each instance of FormSomething has an Id associated with it.

Edit: I guess what I'm really trying to get at is being able to externally close a specific instance of FormSomething.

I'd really appreciate any tips! :D

+3  A: 

There's a Close method on the Form class that you could call.

Sounds like you just need to keep a list of the forms that you have open so that you can refer to them later:

    List<FormSomthing> _SomethingForms = new List<FormSomething>();

    void DisplaySomething()
    {
        FormSomething FormSomething = new FormSomething(SomethingId);
        _SomethingForms.Add(FormSomething);
        FormSomething.Show();
    }

    void CloseThatSucka(int somethingId)
    {
        // You might as well use a Dictionary instead of a List (unless you just hate dictionaries...)
        var form = _SomethingForms.Find(frm => frm.SomethingId == somethingId);
        if(form != null)
        {
            form.Close();
            _SomethingForms.Remove(form);
        }
    }
Dr. Wily's Apprentice
Yeah, but it might be more logical to use a dictionary for this...
Oskar Kjellin
A minor point, the `Remove` would be better off inside the `if (form != null)` test.
ChrisF
Gah! both great points. How silly of me.
Dr. Wily's Apprentice
Hey guys, ok, I built it all up, but it's crashing on form.Close(); I'll get the error message after pulling my code out of a try, any help would be appreciated, thanks!
Soo
Cross-thread operation not valid: Control 'FormSomething' accessed from a thread other than the thread it was created on.
Soo
Added an invoke, fixed, thanks! :)
Soo
+2  A: 

Just keep track of them. A dictionary is the natural collection object. For example:

    Dictionary<int, Form2> instances = new Dictionary<int, Form2>();

    public void OpenForm(int id) {
        if (instances.ContainsKey(id)) {
            var frm = instances[id];
            frm.WindowState = FormWindowState.Normal;
            frm.Focus();
        }
        else {
            var frm = new Form2(id);
            instances.Add(id, frm);
            frm.FormClosed += delegate { instances.Remove(id); };
            frm.Show();
        }
    }
Hans Passant