循环通过每个项目的数组

时间:2014-07-02 00:33:29

标签: arrays vb.net loops

我的ScheduleType_ID存储在这样的数据库中:1~2~3~等 我需要能够访问每个数字(总是从0到9),以便我可以在WinForm上执行某些操作。有一个checkedlistbox控件,这些数字代表需要检查的选项。我下面的代码并没有让我在那里。

 While myReader.Read
     If Not String.IsNullOrEmpty(myReader("SchType_ID").ToString) Then
     SchedArray = (myReader("SchType_ID").ToString).Split("~")
         For i = 0 To SchedArray.Length - 2
            builder.Append(SchedArray(i) & ",")
         Next
     End If
 End While

1 个答案:

答案 0 :(得分:1)

这应该为你做一个没有数组...

 Dim intcount As Integer = 0 'Used to make sure commas are in order
 For Each item As Integer In myReader("SchType_ID").ToString.Split("~")
    If intcount >= 1 Then
      builder.Append(",")
      builder.Append(item.ToString)
    Else
      builder.Append(item.ToString)
      intcount += 1
    End If
 Next

将项目添加到数组的另一个示例

 Dim strArray As New List(Of Integer)
 Dim intcount As Integer = 0 'Used to make sure commas are in order

    'Add items to the array
    For Each item As Integer In myReader("SchType_ID").ToString.Split("~")
        strArray.Add(item)
    Next

    'Add each item to the string builder
    For Each intItem As Integer In strArray
        If intcount >= 1 Then
            builder.Append(",")
            builder.Append(intItem.ToString)
        Else
            builder.Append(intItem.ToString)
            intcount += 1
        End If
    Next

    MessageBox.Show(builder.ToString) 'Only for testing purposes

此处还有适合您的功能

 Public Function BuildArray(ByVal strItems As String) As List(Of Integer)
    Dim lstArray As New List(Of Integer)

    For Each item As Integer In strItems.Split("~")
        lstArray.Add(item)
    Next

    Return lstArray
 End Function

*要使用此功能,您可以这样使用它......

    Dim lstArray As List(Of Integer)
    Dim intcount As Integer = 0

    lstArray = New List(Of Integer)(BuildArray(myReader("SchType_ID").ToString))

    'Add each item to the string builder
    For Each intItem As Integer In lstArray
        If intcount >= 1 Then
            builder.Append(",")
            builder.Append(intItem.ToString)
        Else
            builder.Append(intItem.ToString)
            intcount += 1
        End If
    Next

    MessageBox.Show(builder.ToString) 'Testing purpose only

快乐的编码!