selecting form object through a loop

  • Thread starter Thread starter Shawn
  • Start date Start date
S

Shawn

I'm trying to go through a large number of logically named textboxes
using a loop and cannot figure out how short of explicitly referencing
every single one.
 
Shawn said:
I'm trying to go through a large number of logically named textboxes
using a loop and cannot figure out how short of explicitly referencing
every single one.

Perhaps something like:
For Each ctl As Control In Me.Controls

If TypeOf ctl Is TextBox Then

'do whatever

End If

Next

Be aware that some controls act as containers for other controls and contain
their own collection.
 
You can just loop through all controls on the form , check if that control
is a textbox
then cast it to a textbox control and read and set all properties and
methods just as normall

However note that if you use containers ( panels e.g. ) that you should
process them recursively

example :

Private Sub SetAllTextBoxBackColor(ByVal ctrlContainer As Control,ByVal clr
As Color)


For Each ctrl As Control In ctrlContainer.Controls

If TypeOf ctrl Is TextBox Then

CType(ctrl, TextBox).BackColor = clr

Else

If ctrl.Controls.Count > 0 Then

'this one is a container so process it recursive

SetAllTextBoxBackColor(ctrl, clr)

End If

End If

Next

End Sub

usage :



SetAllTextBoxBackColor(Me, Color.Red)

the above code will find anny textbox on a form wether it is placed on a
panell , tabcontrol or whatever and set the backcolor to red
you can just as easy set or retrieve anny property of the controls you want

HTH

Michel Posseth
http://www.vbdotnetcoder.com
 
Shawn said:
I'm trying to go through a large number of logically named textboxes
using a loop and cannot figure out how short of explicitly referencing
every single one.

The days of being able to sensibly "get at" a Control based solely on
its /Name/ are long gone.

Generally speaking, having the Name of something isn't much use.
Having a /reference/ to the thing itself (through which, of course, you
can ask the object its Name) is much, /much/ better.

Create yourself an array of TextBoxes - or an ArrayList containing
TextBoxes or (VB'2005+) a List(Of TextBox) - containing the ones you
want to work with and loop through that, as in:

Private m_allTextBoxes as New List(Of TextBox)

Private Sub InitialiseFields()
m_allTextBoxes.Add( Me.TextBox1 )
. . .
m_allTextBoxes.Add( Me.TextBox<n> )
End Sub

''' <remarks type="rant" >
''' Is it just me that finds it annoying having "<" and ">" as part
''' of the language these days?
''' How are we supposed to mark non-syntactic bits of example code?
''' "<" and ">" are used for Attributes, "[" and "]" protect reserved
''' words and "(" and ")" have always been part and parcel of Basic...
''' Anyway ...
''' </remarks>

Private Sub Zap()
For Each tb As TextBox in m_allTextBoxes
tb.Text = String.Empty
Next
End Sub

HTH,
Phill W.
 
Back
Top