This code was taken from a forms collection that I use to create multiple instances of a form. For example, the application allows several customer records to be opened at once, but only one instance of every customer. So the full version has a method that allows you to check the object stored in each form's tag property.
When I open a customer record, I store the datarow from the dataset (or you could store just the customer's id) in the tag property. Then, I have a method in the forms collection called IsInstanceInCollection which goes something like this:
VB Code:
Public Function IsInstanceInCollection(ByVal formName As String, ByVal row As DataRow) As Form Dim item As Form Dim formRow As DataRow Dim counter As Integer Try 'loop through the forms collection For Each item In list If item.Name.ToLower = formName.ToLower Then 'if the form names match then retrieve the row formRow = CType(item.Tag, DataRow) 'if the items in the left most columns match then return the form as the correct item If formRow(0) = row(0) Then Return item End If End If Next Catch ex As Exception MessageBox.Show("Error locating the specified instance of " & formName) Return Nothing Finally formRow = Nothing item = Nothing End Try End Function
This returns the instance of the form if found.
The calling code is an If statement that checks to see if the method returns something and if not, will create a new instance to display to the user and stores the relevant data row in the tag property as the new form is loaded.
It is overloaded to work in a variety of different ways.
A cut down version of this to work with the code that staticbob wrote would go something like this:
VB Code:
Public Sub Remove(ByVal formTagObject As Object) Dim frm As Form For Each frm In MyBase.InnerList If frm.Tag = formTagObject Then MyBase.InnerList.Remove(frm) Exit For End If Next End Sub
To use this, I just created a unique string to store in each new form's tag object when instantiating and adding them to the collection.
Hope this clarifies things![]()





Reply With Quote