我创建了2个列表,其中一个列表是由另一列表的对象填充的。当我将详细信息从第二个列表传输到数组,然后对其进行分析时,我遇到了错误。我似乎不明白错误在哪里。
所以我认为问题出在比较时数组初始化和数组转换。
coa = ""
For i = 0 To partab.ListBox2.ListCount - 1
If partab.ListBox2.Selected(i) Then
If coa = "" Then
coa = partab.ListBox2.List(i).tostring()
Else
coa = coa & "," & partab.ListBox2.List(i).tostring()
End If
End If
Next i
Dim arr() As String
Dim arrv() As Integer
arr = Split(coa, ",")
For i = 0 To partab.ListBox2.ListCount - 1
If IsEmpty(arr) = True Then
arrv(0) = 99
Else
If arr(i) = "Vehicle-Vehicle" Then
arrv(i) = 1
ElseIf arr(i) = "Vehicle-Pedestrian" Then
arrv(i) = 2
ElseIf arr(i) = "Vehicle-Bicycle/Others" Then
arrv(i) = 3
ElseIf arr(i) = "Vehicle-Animal" Then
arrv(i) = 4
Else
arrv(i) = 99
End If
End If
Next i
Dim displayar As String
displayar = ""
If IsEmpty(arrv) Then
displayar = 99
Else
For i = 0 To partab.ListBox2.ListCount - 1
displayar = displayar & "," & arrv(i)
Next i
End If
因此代码假定变量coa
的值为空,然后接受listbox2
的值。这些值用逗号分隔并存储在字符串中。然后将字符串转换为数组。
将数组元素与所示的字符串值进行比较,并使用带有相应代码的另一个数组存储这些值。第二个数组是我要分析的数组。
我不确定代码在哪里。
答案 0 :(得分:1)
您的代码中未声明变量coa
。因此,我认为这是一个变体。您在代码开始时为其分配值“”,这使其成为字符串类型的变体。接下来,您的代码检查它是否确实具有空字符串值,因为您刚刚为它分配了该值,所以它看起来是多余的,但是如果确实具有该值,则代码将继续为其分配一个数组。这就变成了数组类型的变体。请注意,它的数组永远不能具有值“”。我建议您将cao
声明为您想要的名称,并对其进行处理。
分配给cao的数组是在ListBox中选择的所有项目的数组。可能不会是几个。通过查看代码无法知道。
但是,For i = 0 To partab.ListBox2.ListCount - 1
尝试从数组cao
读取ListBox中的所有值。仅当选择了列表框中的所有项目时,才应该可行,因为cao
仅包含所选项目。因此,当i大于UBound(cao)时,行If arr(i) = "Vehicle-Vehicle" Then
必须抛出下标错误。
我建议将循环的格式设置为For i = LBound(cao) To UBound(cao)
。这样可以解决此特定错误。可能还有其他人。
答案 1 :(得分:0)
“ arrv”变量没有索引,因为它不是数组。
答案 2 :(得分:0)
我相信您正在使用VB.net。如果是,那么这就是您要尝试的吗?
Public Class Form1
'~~> Adding sample items for demonstration purpose
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With ListBox2.Items
.Add ("Vehicle-Vehicle")
.Add ("Sid")
.Add ("Vehicle-Pedestrian")
.Add ("Sid")
.Add ("Vehicle-Bicycle/Others")
.Add ("Sid")
.Add ("Vehicle-Animal")
End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim coa As String = ""
Dim displayar As String = ""
'~~> Loop though selected items of the listbox
For i As Integer = 0 To ListBox2.SelectedItems.Count - 1
coa = coa & "," & ListBox2.SelectedItems(i)
Next i
'~~> Check if there is something or not in coa
If String.IsNullOrEmpty(coa) Then
displayar = 99
Else
Dim arr = Split(coa, ",")
Dim arrv() As String
ReDim arrv(UBound(arr))
Dim n As Integer = 0
'~~> Loop though the array and check it's values
For i As Integer = 0 To UBound(arr)
Select Case arr(i)
Case "Vehicle-Vehicle": arrv(n) = 1
Case "Vehicle-Pedestrian": arrv(n) = 2
Case "Vehicle-Bicycle/Others": arrv(n) = 3
Case "Vehicle-Animal": arrv(n) = 4
Case Else: arrv(n) = 99
End Select
n += 1
Next i
'~~> Get the complete string without looping
displayar = Join(arrv, ",")
End If
MessageBox.Show (displayar)
End Sub
End Class
如果我选择所有项目,则输出将为99,1,99,2,99,3,99,4
,如果我不选择任何内容,则输出将为99