SUMMARY
Microsoft Visual C# .NET or Microsoft Visual C# 2005 does not provide a built-in
collection for
Form objects that are used in a project. This article describes how
to build a custom collection class that essentially supports the functionality
of a Forms collection.
back to the
topCreate the Custom Forms Collection
The first step to create a custom collection class in Visual C#
.NET or Visual C# 2005 is to add a class to the project. To prevent objects other than
Form objects from being added to the collection, make sure that this class inherits the
CollectionBase class and then shadows the
Add method.
The
following code illustrates how to add this class:
public class FormsCollection : CollectionBase
{
public Form Add(Form FormObject)
{
base.List.Add(FormObject);
return(FormObject) ;
}
public void Remove(Form FormObject)
{
base.List.Remove(FormObject);
}
}
back to the topCreate an Instance of the Forms Collection Object
When you run the project, you must create an instance of the custom
collection class to add
Form objects to it. The easiest way to make sure that the collection
is created before any forms are displayed is to set the startup object for the
project to the class that contains
Main in the
Project Properties dialog box.
The
following code illustrates how to create an instance of a
Forms collection object:
public FormsCollection Forms;
static void Main()
{
Forms = new FormsCollection();
Application.Run(new Form1());
}
back to the
topAdd and Remove Forms from the Collection
Before you add a
Form to the collection , you must add a
Form to
the project from the
Project menu. After this, you must modify the
constructor so that the
Form can add itself to the collection, and you must modify the destructor
so that the
Form can remove itself from the collection.
The following code
illustrates how to do this:
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
Forms.Add(this);
//
// TODO: Add any constructor code after InitializeComponent call
//
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
Forms.Remove(this);
}
back to the topUse the Forms Collection
The following example loops through the
Forms collection and displays the
Name property of any control on the form:
Form LoopForm ;
Control LoopControl;
foreach ( Form LoopForm in Forms)
{
foreach (Control LoopControl in LoopForm.Controls)
{
MessageBox.Show(LoopControl.Name);
}
}
back to the
top