Question Putting each character in string into seperate textbox - help

124112

New member
Joined
Feb 27, 2010
Messages
3
Programming Experience
1-3
I have a program where a user puts a string into a textbox, and then character one goes into Textbox1, char2 goes into TB2, char3 goes into TB3, etc.

I have a For loop that gets all of my textboxes that are used for this, and I have my for loop that is supposed to go through my string character by character.

Here is my code:

VB.NET:
        Dim impText As String
        Dim i As Integer
        Dim txtLength As Integer
        Dim num As Integer
        Dim oneChar As Char
        Dim tb = DirectCast(Me.Controls("TextBox" & num), TextBox)
        impText = Trim(TextBox171.Text)
        txtLength = impText.Length
        oneChar = impText.Chars(i)

            For i = 0 To txtLength - 1
            For num As Integer = 1 To 136
                oneChar = impText.Chars(i)
                tb.text = oneChar
            Next i

That basically shows what I am trying to do.

Could anyone help me who knows what is going on? Thanks.
 
Dim tb = DirectCast(Me.Controls("TextBox" & num), TextBox)
This line look up the control named "TextBox0" and assigns the reference to "tb" variable.

Later, inside the loop, when you refer to variable "tb" the expression above is not re-evaluated, you set Text for the "TextBox0" control every iteration. To look up a different control each iteration you must do the look up inside the loop.
 
See if this will work for you:

VB.NET:
	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		Dim mystring As String = TextBox1.Text
		Dim N As Integer = mystring.Length
		If N > 8 Then N = 8 'assuming 8 textboxes available, will use 1st 8 characters
		Dim strarray(N) As String
		For x As Integer = 0 To N - 1
			strarray(x) = mystring.Chars(x)
		Next x
		Dim ch As Integer = 0
		For Each ctl As Control In Controls
			If TypeOf ctl Is TextBox Then
				Dim txt As TextBox
				txt = CType(ctl, TextBox)
				txt.Text = strarray(ch)
				ch += 1
			End If
		Next ctl
	End Sub
 
NOTE: The last For Each loop can be shortened. It is not necessary to declare the textbox by name:


VB.NET:
		For Each ctl As Control In Controls
			If TypeOf ctl Is TextBox Then
				ctl.Text = strarray(ch)
				ch += 1
			End If
		Next ctl


Also, the above will put the letters in reverse order of how the texboxes were placed on the form. To place them in correct order, you can do this:

VB.NET:
		Dim ch As Integer = N	'list in correct order of control placement
		For Each ctl As Control In Controls
			If TypeOf ctl Is TextBox And ch > 0 Then
				ch -= 1	'will omit TextBox1, which was placed first (N)
				ctl.Text = strarray(ch)
			End If
		Next ctl
 
Last edited:
Back
Top