开发者

How can I loop through all the open instances of a particular form?

I need to update a ListBox of a Form2 created dynamically. Let's say that in the event where I have to update this ListBox (in Form1 of course) I don't have a reference of this Form2 so I can't call the UpdateList method (and no, I can't make it static).

I don't even know if there is a Form2 opened, it could be or not.

What do you suggest?

Is there a way to loop through all the open istances of Form2?

Code Sample:

//Form1

public void event()
{
    //UPDATE FORM2 LISTBOX
}

//SOMEWHERE I开发者_Go百科N FORM1

Form2 runTime = new Form2();

//Form2

public void UpdateList()
{
    //UPDATE LISTBOX
}


I'm not sure what exactly do you want to implement. But it seems to me that you can just iterate through the collection of opened forms:

var formsList  = Application.OpenForms.OfType<Form2>();
listBox.Items.AddRange(formsList.Select(f=>f.Text).ToArray());

This line will give you the IEnumerable of all open Form2 instances in your application. You might want to use your own string representation (not the form caption used in the snippet above)


I would add all Form2 references to an arrayList (other some other collection class, e.g. List)

/// form1
List<Form2> list = new List<Form2>();

void createForm2(object sender, EventArgs e)
{
     Form2 newForm = new Form2();
     newForm.FormClosed += new FormClosedEventHandler(form2_closed);
     list.add(newForm);
}

void updateListBox()
{
    for each (Form2 curform in list)
    {
         curform.updateListbox();
    }
}

void form2_closed(object sender, FormClosedEventArgs e)
{
   list.Remove(sender);
   updateListBox();  // in case a form2 instance is closed, recall method
}

/// form2
public void updateListbox()
{
    // enter code here ...
}

In case an Form2 instance is closed, remove it from the list (here: on formClosed event)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜