bonny bonny - 1 year ago 68 Question

Select Textbox using For Loop

Sorry this is weird and silly question but I need a solution of this...

I have 30 textboxes named as Txt1,Txt2,Txt3,...,Txt30

I have to fill textbox as Txt1.text = 0 on button click..

Is there any way like
On Button Click

Dim i as Integer
For i = 1 to 30 '----- Possible in string but don't know if possible in textboxes
Txt(i).text = 0

Or I have to write all 30 lines like

Txt1.text = 0
Txt30.text = 0

I don't know how this question asked, maybe Question improper.

Thanx in Advance...

Answer Source

If the textboxes are all contained in Controls collection of the Form, then it is really easy to loop over them

For Each(t in Me.Controls.OfType(Of TextBox)())
   t.Text = "0"

Of course the advantage of this approach is that you don't have to worry if you add other textboxes to your form. They will be found using the foreach loop without having a fixed top limit.

And, if not all of your textboxes should be included in the loop, then you can simply use the Tag property of the textboxes that you want to use. For example, if you set the Tag property to the string "Y", then you can change the foreach loop to find only the controls with the matching Tag property

For Each t in Me.Controls.OfType(Of TextBox)() _ 
                         .Where(Function(x) x.Tag = "Y")
   t.Text = "0"

The two solutions above works well if all your textboxes are contained in the same container (Form, GroupBox or Panel), instead, if these textboxes are dispersed in different containers (some in a groupbox, others in a panel etc) then you can build a List(Of TextBox) variable filling it with the textboxes instances and use it when the need arise

Dim myTexts = New List(Of TextBox)() From  { Txt1, Txt2, Txt3, ....}

And loop over this variable