Variable outside the bounds of the matrix

2

I'm trying to put the items in positions of an array, but I get the error that the variable is outside the bounds of the array. I do not know how to fix the bug and I need help.

Follow the code:

Dim posicao As String = String.Join("", itens)
Dim separa As String()
Dim contagem As String

contagem = ListBox1.Items.Count

Dim i As Integer
For i = 0 To contagem
separa = Split(posicao, ";")
cpf = separa(0)
nome = separa(1) 'O erro ocorre aqui.
anonasc = separa(2)
Next

TextBox1.Items.Add(cpf & ";" & nome & ";" & anonasc)

The program does not point me to code errors. I'm parsing the items variable, which gets the lines of a .txt file.

The file_file variable receives the .FileName from an OpenFileDialog.

Variable itens :

Dim local_arquivo As String
itens = (My.Computer.FileSystem.ReadAllText(local_arquivo, System.Text.Encoding.Default)).Replace(vbLf, String.Empty).Split((CChar(vbCr)))
ListBox1.Items.AddRange(itens)
    
asked by anonymous 02.05.2016 / 00:19

2 answers

2

Clearly the data being analyzed does not have the expected semicolons. This is an ill-formed fact, something that can happen.

Unless it is a misinterpretation of what the code should do, the correct one is to check before accessing the data. You have to decide what to do if the data is poorly formed, probably indicating an error. That is, you can not just access separa(0) , separa(1) and separa(2) , before doing this you have to see if the size of the array is 3. If it is not, you have to algorithm and inform that the file is invalid.

Another detail to be analyzed is whether this For is serving for anything. I do not think so. Maybe it's intention to do something with it, but at the moment it's useless.

With editing, the problem can be different. I did a test with the data passed and everything works. I had to change some things, the code did not compile.

The answer is still valid because even if the data is not in trouble now, one day it may be.

    
02.05.2016 / 00:59
1
Dim posicao As String = String.Join(";", itens)
Dim separa As String() = posicao.split(;)
Dim contagem As Integer = separa.count

 cpf = separa(0)
 nome = separa(1) 
 anonasc = separa(2)

for x as integer = 0 to Contagem-1
    textbox1.text = textbox1.text & ";" & separa(x)
next
    
03.05.2016 / 17:39