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
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);
}
}
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();
}
}
精彩评论