Markowitz Markowitz - 22 days ago 6
Vb.net Question

For next loop on numbered textboxes

I want to simplify the following code:

TextBox321.SelectionStart = 0
TextBox322.SelectionStart = 0
TextBox323.SelectionStart = 0
TextBox324.SelectionStart = 0
TextBox325.SelectionStart = 0
TextBox326.SelectionStart = 0
TextBox327.SelectionStart = 0
TextBox328.SelectionStart = 0
TextBox329.SelectionStart = 0
TextBox330.SelectionStart = 0


I need loop code like following;

For TextBox321 to TextBox330
.SelectionStart = 0
Next


My system:


  • winform app with visual-studio 2010 Ultimate, .Net Framework 4


Answer

The Following code solved the problem:

For i = 321 To 330


        Dim ctrlCollection As List(Of TextBox) = Me.Controls.Find("Textbox" & i.ToString, True).OfType(Of TextBox).ToList()

        For Each Ctrl As TextBox In ctrlCollection

            Ctrl.SelectionStart = 0
            ' if you want to select one character from the begining
            ' Add this code
            ' Ctrl.SelectionLength = 1
            'If you want to remove selection
            ' Try using Ctrl.Select(0, 0) instead of Ctrl.SelectionStart = 1

        Next

    Next