Reputation: 137
Assume that I have the following string in TextBox1: FPO100200%10&FORD*
Now, i have 2 more textboxes that gets data from substrings of textbox1. I have the following code:
Public Class Form1
Private Function textmoves(mytext As String, indexchar As String)
Dim Index As Integer = mytext.IndexOf(indexchar)
Return Index
End Function
Private Sub Splittext()
Dim text As String = TextBox1.Text
TextBox2.Text = text.Substring(0, textmoves(text, "%"))
TextBox3.Text = text.Substring(textmoves(text, "%"), textmoves(text, "&"))
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Splittext()
End Sub
End Class
Im trying to get in texbox2 the substring FPO100200, then in texbox3 the substring 10.
As soon as I added the line with textbox3, it threw me an argument out of range error. Can you tell me what im doing wrong? Thanks alot!
LE: Also, how can I make that textboxes to populate with data when text changed in textbox1, automatically, without pressing the button?
Upvotes: 1
Views: 691
Reputation: 726569
Second parameter is length, not end position. The reason the first expression worked with position is that the initial index is zero.
To get "10"
use
TextBox3.Text = text.Substring(textmoves(text, "%")+1, textmoves(text, "&")-textmoves(text, "%")-1)
or better
Dim pos As Integer = textmoves(text, "%")
TextBox2.Text = text.Substring(0, pos)
TextBox3.Text = text.Substring(pos+1, textmoves(text, "&")-pos-1)
Upvotes: 1
Reputation: 2333
Your second parameter is the Index of the & when you start at index 0 but you're begining at the index of %. So you need to substract %Index from &Index.
TextBox3.Text = text.Substring(textmoves(text, "%"), textmoves(text, "&") - textmoves(text, "%"))
Upvotes: 1