I am trying to upgrade code from VB4 to VB.NET. I am a bit confused by the collection (I am used to an array). On a form, I have multiple textboxes and multiple comboboxes. What I want to do is get these into two arrays, (one for the textboxes and one for the comboboxes), and be able to access each control in the collection individually (i.e. to add items to a specific combobox). I am trying to access the form control collection.
For counter =0 to controls.Count to then assign the different textboxes and comboboxes to their collection, but I don't seem to be able to get this to work?
So how do I do it? Thank you for your help.
I can understand your bemusement to this issue. It took me a few weeks to work this out before finally getting to grips with all the changes.
To be honest though you are very close to a solution....
As you discovered, the form object contains a collection called 'CONTROLS,' and within this the property are the controls themselves. I would advise keeping the information in there and using it. The following code will do what I think you are after achieving:
Dim x As Control For Each x In Me.Controls Select Case (x.GetType.ToString) Case "System.Windows.Forms.TextBox" Dim y As TextBox = CType(x, TextBox) MsgBox(y.Text) Case Else ' Do nothing End Select Next
Note that I used the CTYPE function to change the generic object x,' which is of type CONTROL to the type that is desired (in this case a textbox). You should note that the case uses the fully qualified name of the type. So if you were to add comboboxes to this, then you would perhaps add the case "System.Windows.Forms.ComboBox." Hope that helps.
Dig Deeper on Win Development Resources
Related Q&A from Samuel Colak
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.