2

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 IN FORM1

Form2 runTime = new Form2();

//Form2

public void UpdateList()
{
    //UPDATE LISTBOX
}
Myles Gray
  • 8,711
  • 7
  • 48
  • 70
raz3r
  • 3,071
  • 8
  • 44
  • 66
  • 1
    It sounds like you need to figure out a better way to manage your forms. "An instance or several might or might not be open, I don't really know" sounds like an unmaintainable mess. You're doing OOP wrong. – Cody Gray - on strike Jan 10 '11 at 12:32
  • You're right, in fact this question is more a curiosity than a real needing ^^ – raz3r Jan 10 '11 at 13:14

2 Answers2

8

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)

default locale
  • 13,035
  • 13
  • 56
  • 62
3

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)

Pilgerstorfer Franz
  • 8,303
  • 3
  • 41
  • 54
  • Answer given by MAKKAM sounds pretty good too (Application.OpenForms....) If you want to react on some form2-events this solution might also help you. – Pilgerstorfer Franz Jan 10 '11 at 12:40
  • I thinked about the Array too but I wanted to implement something new and "unusual", thanks anyway! – raz3r Jan 10 '11 at 13:16
  • 2
    This is the proper way to do it, although the List<> is overkill for the question. Read the comments on makkam's answer why this is a much better way of doing it. – Hans Passant Jan 10 '11 at 14:00