Mark Tr
Mark Tr

Reputation: 63

Create multiple instance of one form?


Consider the following code:

    for (int i = 0; i < 10; i++)
    {
        Form1 frm = new Form1;
        frm.Show();
    }

The question is how can i manage these instances which has been created?
Example: After these instances have been created i want to get a ID of each instance, then user will choose which instance will be show!
Thanks in advance!

Upvotes: 0

Views: 282

Answers (2)

Steve
Steve

Reputation: 216263

You say that you want to show one of the forms after the user choose the "ID" but you call Show for all of them in your loop. So you have all of them shown not just the one choosen. I think you should remove that call to Show.
But in this case the automatically maintained OpenForms collection is empty (or at least doesn't contain the Forms created in your loop) so you need a custom collection of these forms.

Finally you need to set something that acts as an ID for your dynamically created form otherwise you are not able to retrieve it from the user input.

List<Form1> form1List = new List<Form1>();
for (int i = 0; i < 10; i++)
{
    Form1 frm = new Form1();
    frm.Name = "Form1_Instance_" + i.ToString();
    frm.Text = frm.Name;
    frm.Tag = i;
    // Do not show it
    // frm.Show(); 
    // Add it to your list
    form1List.Add(frm);
}

// Now suppose that your code has a TextBox from which your user types the ID of the form

string temp = TextBox1.Text;
int num;
if (Int32.TryParse(temp, out num))
{
    if(num >= 0 && num <= 9)        
    {
       Form1 f = form1List.FirstOrDefault(x => x.Tag.ToString() == num.ToString());
       if(f != null)
           f.Show();
    }
}

Upvotes: 0

Andrey Korneyev
Andrey Korneyev

Reputation: 26846

Just save these instances into some collection, and then you will be able to reach them.

Something like:

var forms = new List<Form1>();
for (int i = 0; i < 10; i++)
{
    var frm = new Form1();
    forms.Add(frm);
    frm.Show();
}

So later you can get your desired i-th form as forms[i].

But note - you will have to care about removing form from this collection when it is not needed anymore, otherwise it will prevent garbage collector from collecting it.

Upvotes: 2

Related Questions