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
Next

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.

Recommended Answers

All 6 Replies

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

    ' do something with tb

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

    ' do something with tb

Next

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.

Ex:
Dim tb As Textbox
tb("TextBox2").SetFocus

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
Next

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

Next

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
next

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

TIA

Hx

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.