views:

217

answers:

2

If I have a collection of forms (myForms) and I want to switch the position of two forms in the collection (say items 3 and 4 for example), I would expect that the following code would work:

Dim temp as Form
Set temp = myForms(3)
Set myForms(3) = myForms(4)
Set myForms(4) = temp

But that doesn't work. It fails at the third line with the error "Controls property is read only." If I change the line to:

myForms(3) = myForms(4)

I get a type mismatch error instead.

+2  A: 

You can't actually swap around items in the controls collection in VB6. You need to use the Add and Remove functions associated with each. Check out this article:

http://support.microsoft.com/kb/190670

Hope this helps!

mattbasta
This article is about dynamically adding controls to a form. How is it relevant to swapping items in a collection?
CMH
+1  A: 

If myForms is a standard collection: Dim myForms as New Collection (which is actually different from the controls collection) and you've added the forms using: myForms.Add frmOne, myForms.Add frmTwo, etc then (yes) you do need to use the Add and Remove methods because of the way the collection references the added objects.
Otherwise the interpretation is that you actually want to replace one form with another and this is not allowed. You can't say: Set frmOne = frmTwo unless these are actually variables of type Form.
Why do you need to switch the order? Are you referencing the item numbers somewhere? Would using a Dictionary to collect the forms and reference them by a key be useful?
Sorry, lots to consider when dealing with forms and instances of forms. :-)
PS. The type mismatch is simply because both items are objects and need to be 'Set'.

CMH
The order matters because a number of times in the program, lists are populated with the forms and users are supposed to be able to rearrange the order of the forms. If I can simply swap the order of the forms in the collection, then every time a list is populated, the order will reflect the user's changes.
Everett