Software Development

Iterating through all controls on the form with VB.NET

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!

20 comments
dej
dej

but i got it. i tried again the code of tony and would you believe it never caught the radio button. (i had all of the radio buttons not in the form but in a group box on the form!) when i put a radio button directly on the form it (tony's code) worked!! i then found from google a way to scan through the control when it is a groupbox looking for radio buttons. thanks to both of you. i am slow but verry appreciative. and as tony pointed this is reallyl the way do this and not with the hack tag. david

dej
dej

i am not looking at a groupbox but at an element of controls. the problem is not typedef since i know the ctrl is a radio button since i have only set the tags of radiobuttons to rb and tag is fortunately a member of control. the problem i believe is in directcast since you are trying to cast a member of controls to a radio button which i don't think is possible. think for a second how do you make a cast from one type to another. the thing you are casting from -- ctrl-- would have to have at least a checked member but i do not think an element of controls has a checked member. and if it doesn't there is no way that you are going to cast the thing into a radiobutton that has a checked member. this might be similar to trying to cast a long = 123456 into a char. no way. what i said above may not make sense to you and if it doesn't let me know david

dej
dej

i have the following code For Each ctrl In Controls controljstring = ctrl.Text 'now knowing ctrl is a radio button i want to find ' its checked property which you can do with radio buttons 'but ctrl.checked is not valid Next thanks

gdkelly
gdkelly

Yes you can interate the controls but you cannot retrieve the .modified property of a textbox for some reason and that's what i need. Any suggestions

thewebpagedeveloper
thewebpagedeveloper

You have to setfocus to the control prior to referencing that control for assignment of values (VBA)

PetePixxx
PetePixxx

Doesn't work for web forms. error message is "'Text' is not a member of 'System.Web.UI.Controls'" How are webforms, and their control structure, different? ~p

treymacksc
treymacksc

I have little experience in the .Net languages, but I believe I've heard that the .Controls collection of a Container (Form, in this case) only lists the Controls directly contained by the Container. So, if one of those TextBoxes were under a Frame (I think they're called Panels in .Net?), this box would not be changed. Am I right? Do you need to use recursion? I can safely say that this code would work perfectly in VB6, however.

Tony Hopkinson
Tony Hopkinson

.net introduced the container concept to vb. In VB6, it was a bit of a mess, like a lot of other things... Anyway you got there, can't stress this enough though if you want to learn, do it from your and our mistakes. Just think about how much more you know after these few than you did before. You could have read a .net book 'til your eyes bled and learnt waaay less. Me and Slayer_ suffer I mean enjoy learning opportunities every day. :p

Slayer_
Slayer_

You first check if its a radio button, then you cast it. If your worried that might fail, wrap it in a try/catch block. Using tags to figure out if its a radio button is a poor way to do it, if you insist on doing something like that, check the control name instead and use a naming standard on your controls.

Tony Hopkinson
Tony Hopkinson

you are now knowing because you haven't had an exception, that ctrl has a text property. Something like Dim rb as RaidioButton for each ctrl in Controls rb = ctrl as RadioButton if rb Nothing if rb.Checked 'Dosomething else 'DoSomethingelse endif next I'm not a vb guy, but the idea is sound.

flevitan
flevitan

First: sorry for my English. I speak spanish. Hope someone will correct my mistakes. This Sub will do: Public Sub CtrlsSetFont(ByVal Container As Control) Dim C As Control For Each C In Container.Controls If TypeOf C Is Label Then C.Font = pubLblFont ElseIf TypeOf C Is TextBox Then C.Font = pubTBFont ElseIf TypeOf C Is GroupBox Then C.Font = pubGboxFont ElseIf TypeOf C Is ListBox Then C.Font = pubLstFont ElseIf TypeOf C Is Button Then C.Font = pubBtnFont End If If C.HasChildren Then 'Is a container control; call myself CtrlsSetFont(C) End If Next End Sub May try with 'Select Case TypeOf C' and Case Is ...

Tony Hopkinson
Tony Hopkinson

this will only work for one container and yes it would have worked in VB6, which is another reason why it was bit crap. Not just panels, any of the components categorised as containers in the toolbar.

dej
dej

tried it but the statement rb = ctrl is apparently not a valid cast. too bad it didn't work. david

dranfu
dranfu

Thanks for your reply! I learn more from you guys than I do in class.

Tony Hopkinson
Tony Hopkinson

syntax. If the container class has a font property and the contained items haven't had a different font assigned to them, then changing the container's font will change all it's children's.

Tony Hopkinson
Tony Hopkinson

on your form has a tag of "rb" then doesn't it. I used typeof in my example, not rely on some tag being set at design time, which as you've just discovered can go a bit wrong. You need to step back a bit, don't look at the code you think you've written look at the code that's there. GroupBox and RadioButton aren't the same thing...

dej
dej

coded your suggestion this is the code i tried. it does compile (vb.net) but has (run time) exception at the line *** dim s as string For Each ctrl In Controls s = ctrl.Tag ' set the tags in radiobuttons to "rb" If ctrl.Tag = "rb" Then rb = DirectCast(ctrl, RadioButton) *** exception End If Next this is the error message at the ***line Unable to cast object of type 'System.Windows.Forms.GroupBox' to type 'System.Windows.Forms.RadioButton'. i am beginning to think that the ctrl in controls does not have a checked data member and so no amount of casting is going to work since the information may not be there. thank you for your help. i have just started working with vb.new and find an enormous over vb6 that i have been using for a number of years.

Tony Hopkinson
Tony Hopkinson

Turns out there's no as operator in vb.net, well hey I knew there was a reason I used a proper language. try if TypeOf ctrl is RadioButton rb = DirectCast(ctrl, RadioButton) if rb.Checked 'etc.. endif endif Put some effort in or give up now, ffs. Took me about 30 seconds to google that.

Tony Hopkinson
Tony Hopkinson

Haven't had to do it yet, but .net is mant to be quire good at internationalisation even to the point of loading and unloading modules on the fly so you can pick a language set up from within the application. If you are doing a lot of this I'd be tempted to pass in a text id and a desired language id and keep the possibilities in a collection. It will be more efficient than doing string matches, though it would introduce a maintenance problem.

bill.dickson
bill.dickson

I am using something similiar to this to show tool tips in different languages. A tool bar is a special container that does not .HaveChildren. To change the Tooltips you need to: If TypeOf ctl Is ToolBar Then Dim tbb As ToolBarButton, tb As ToolBar tb = ctl For Each tbb In tb.Buttons tbb.ToolTipText= translatefunction( tbb.ToolTipText) Next End if

Editor's Picks