If I had 5 text boxes on a form, TextBox1...TextBox5, is there a method to do something like this?

Dim strFld As String
For intFor = 1 to 5
  strFld = "TextBox" & intFor
  Me(strFld).Text = intFor

It doesn't like the line of Me(strFld) but I figure there must be a way to reference a field via a variable instead of hardcoding the field name.

8 Years
Discussion Span
Last Post by __avd
For Each tb As TextBox In Me.Controls.OfType(Of TextBox)()

    ' do something with tb


Thanks for the reply. I like seeing a method that filters the controls and permits enumeration. It works, kindof, except that it threw 1 into Textbox2 and 2 into Textbox1.

Is there a way to specify the control. Let's say you had Textbox1 and Textbox2. Depending on the value of a variable, you want to set focus to the control name that the variable is referencing.

Dim tb As Textbox

That doesn't work either. I figure there's a way work with a control using a variable instead of the hardcoded name.


You can order the textboxes like this

For Each tb As TextBox In Me.Controls.OfType(Of TextBox)().OrderBy(Function(t) t.Name)
    ' do something with tb

To grab a given control via its string name, you can do something like this

Dim textBox As TextBox = Me.Controls.Find("textBox1", True).OfType(Of TextBox).First()

Thanks much for your input. It's not an simple as I expected but you provided me with something I can play around with.


I was looking for something like this and found your post:

start quote:

For Each tb As TextBox In Me.Controls.OfType(Of TextBox)()

    ' do something with tb


end quote.

I was really pleased! I thought this was the perfect answer.
But when I tried to use it I got the error:

'OfType is not a member of System.Windows.Forms.Control.ControlCollection'

I'm using verion 3.5 of the .NET framework

All my text boxes are named in the style txb_name, can I search for controls with txb in their name? The following code doesn't work either:

For Each tb As TextBox In Me.Controls.Find("txb", True)
'do something with tb

Have you got any ideas why your solution didn't work for me, or an alternative that will?



Edited by mike_2000_17: Fixed formatting


Hi HappyMe.

I'm glad you got it helpful.
Please do not resurrect old threads. Please Do not hijack another thread to ask your question but start your own thread instead. If you have any questions please ask. .... You are welcome to start your own threads.

Thread Closed.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.