Catalin Cernat Catalin Cernat - 5 months ago 29
Vb.net Question

Substring - argument out of range exception - startIndex parameter

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?

Answer

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)

Demo.