creating an array of forms

R

Rich P

In VB.Net I do the following to get an array of existing forms:

Dim frm() As Form
frm = New Form() {Form1, Form2}

How to do this in C#? I tried

Form[] frm;
frm = new Formp[] {Form1, Form2}

but get an error

'WindowsApplication1.Form1' is a 'type' but is used like a 'variable'

Rich
 
U

uncleSally

How to do this in C#?  I tried

Form[] frm;
frm = new Formp[] {Form1, Form2}

Hi Rich,

Why not use the existing FormCollection of the Application object :

Application.OpenForms

Every form created during the application lifetime will be there (once
it has been 'Shown or its .Visible property set to to 'true), even if
the form later has :

..Visible = false;
..Enabled = false;

The only way it will be removed from this FormCollection at runtime is
when the user closes the form at, or when you call 'Close on it at run-
time, or when you call 'Dispose on it at runtime.

If you are wanting to build a list of only certain types of Forms, you
can always parse this list and check the type using 'getType, or
beginning with FrameWork 3.5 you can use 'ofType<Type> which returns
an IEnumerble.

http://msdn.microsoft.com/en-us/library/bb360913.aspx

Example : you wish your current list of all forms of type Form2 to be
updated :

IEnumerable<Form2> myForm2List =
Application.OpenForms.OfType<Form2>();

If you wish to iterate over it :

foreach (Form2 myTargetForm2 in myForm2List)
{
Console.WriteLine("instance of form 2 found : Text = "
+ myTargetForm2 .Text);
}

Of course you could write a handler for the Close event of your
special types of Form that would remove them from this list.

To do that you need to convert the IEnumerable to a List<Type> :

List<Form2> theALForm2 = myForm2List.ToList<Form2>();

theALForm2.RemoveAt(0);

Note : I do not claim any great expertise in this area, and I hope
we'll see a post on this topic that can enlighten us both with a
better way :)

best, Bill
 
J

Jeff Johnson

I figured it out:

frm = new Form[2] { new Form1(), new Form2() };

When initializing an array in the declaration, there's no need to specify
the number of members. you can just do

frm = new Form[] { new Form1(), new Form2() };
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top