Iterating through all controls on the form with VB.NET
Takeaway: Irina Medvinskaya presents a simple way to change all the controls on a form in runtime with VB.NET.
If you've ever had to change all the controls on a form in runtime, you know how tedious it can be to modify the controls one by one. Here's a simple way to perform this useful function with VB.NET.
Controls collection
The form maintains a collection of controls that you can utilize to loop through in order to change a certain property that you want to update in runtime.
For example, add two textboxes to a form and add the following code:
Private Sub SetControls()
Dim cControl As Control
For Each cControl InMe.Controls
If (TypeOf cControl Is TextBox) Then
cControl.Text = "abc"
End If
Next cControl
End Sub
Figure A shows what you will see when you run the code.
Figure A |
![]() |
In the example, I define the variable cControl as a Control object. I then create a for loop that will check all the controls on the form to see if the type of the control is a TextBox. For all the TextBox controls, I set its Text property to value "abc"; so, the Text property would be set to "abc" for as many TextBox controls as you have on the form. You can follow a similar procedure for setting other properties or use it for different control types.
Miss a tip?
Check out the Visual Basic archive, and catch up on the most recent editions of Irina Medvinskaya's column.
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!
Print/View all Posts Comments on this article
SponsoredWhite Papers, Webcasts, and Downloads
- Realize the Power of Truly Mobile Operations PC Connection
- 2008 IT Salary and Skills Report Global Knowledge
- 7 More Red Hat Linux Tips and Tricks Global Knowledge
Article Categories
- Security
- Security Solutions, IT Locksmith
- Networking and Communications
- E-mail Administration NetNote, Cisco Routers and Switches
- CIO and IT Management
- Project Management, CIO Issues, Strategies that Scale
- Desktops, Laptops & OS
- Windows 2000 Professional, Microsoft Word, Microsoft Excel, Microsoft Access, Windows XP,
- Data Management
- Oracle, SQL Server
- Servers
- Windows NT, Linux NetNote, Windows Server 2003
- Career Development
- Geek Trivia
- Software/Web Development
- Web Development Zone, Visual Basic, .NET

