Results 1 to 4 of 4

Thread: How can I use For Each for simultaneous things.

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jun 2015
    Posts
    73

    How can I use For Each for simultaneous things.

    Hello everyone,

    I'd like to know if it's possible to use for each for simultaneous things, and if it is how.

    For example I have a for each statement.

    For each S as String in listbox1.items.item

    msgbox(s)

    next

    So what I'd like to have is

    For each S as String in listbox1.items.item and listbox2.items.item

    msgbox(s) 'Has to output Listbox1 item and listbox2 item next to eachother.

    next

    If you do know how to do this, please let me know.
    Sincerly,
    Paramalodux.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: How can I use For Each for simultaneous things.

    No, that's not possible and it doesn't even make sense. If you have a round hole then use a round peg, not a square one. Use a For loop. You can then use the loop counter to index both Items collections and simply concatenate the two values.

  3. #3
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: How can I use For Each for simultaneous things.

    What JMC means is you can't make a For Each loop have two collections it iterates. But you can use a For loop that looks like this:
    Code:
    For i As Integer = 0 To listBox1.Items.Count
        Dim item1 As String = listBox1.Items(i).ToString()
        Dim item2 As String = listBox2.Items(i).ToString()
    
        ' Do your stuff
    Next
    Be mindful the above is only 'safe' if both listboxes have the same number of items. If they're different sizes, you have to write your code a little differently, but it's a little different every time so there isn't a "one true example" to show.

  4. #4
    Hyperactive Member Vexslasher's Avatar
    Join Date
    Feb 2010
    Posts
    429

    Re: How can I use For Each for simultaneous things.

    Here is how you can do that last part and prevent errors.
    vb.net Code:
    1. If ListBox1.Items.Count = ListBox2.Items.Count Then
    2.             For i As Integer = 0 To (ListBox1.Items.Count - 1)
    3.                 MsgBox(ListBox1.Items(i).ToString & " and " & ListBox2.Items(i).ToString)
    4.             Next
    5.         Else
    6.             MsgBox("The list boxes didn't have an equal amount of items cannot run this.")
    7.         End If

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width