Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
I should be able to amend the data displayed in the list box, so I've planned that when selecting each row of data, this row of data would be split and copied into text boxes (txtBox1,txtBox2 and so on)
I have used the code below to do so, at first it did the job however lately an error keeps popping "Index was outside the bounds of the array" and the last line of code is pointed at. Let me know if anyone can help, thank you.

What I have tried:

Dim array(5) As String
     Dim strRecord As String = ("")
     strRecord = ListBox1.SelectedItem
     array = strRecord.Split(",")
     For N As Integer = 1 To 5
         Dim txtBoxN As TextBox = Me.Controls.Find("txtBox" & N, True).FirstOrDefault
         If Not IsNothing(txtBoxN) Then
             txtBoxN.Text = array(N - 1)


         End If
     Next
Posted
Updated 7-Feb-18 11:00am

1 solution

If you would like to split listbox item into parts, use ListBox.SelectedIndexChanged Event (System.Windows.Forms)[^]
Then, inside that event, paste below code:
VB.NET
Dim curItem As String = ListBox1.SelectedItem.ToString()
Dim parts As String() = curItem.Split(New String(){","}, StringSplitOptions.RemoveEmptyEntries)

For i As Integer = 0 To parts.Count()-1
    Dim txt As TextBox = DirectCast(Me.Controls("txtBox" & i+1), System.Windows.Forms.TextBox)
    txt.Text = parts(i)
Next


You've got "Index was outside the bounds of the array", because your for-next loop starts from one and exceed the number of elements in array. See important note from MSDN:
Quote:
The indexes of an array range from 0 to one less than the total number of elements in the array.


More:
DirectCast Operator (Visual Basic) | Microsoft Docs[^]
Arrays in Visual Basic | Microsoft Docs[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900