More VB Help Please - Combo box being funny!

Associate
Joined
6 Dec 2007
Posts
2,103
Hi again, just another quick question. This code:

Code:
        For i = 0 To i = (listBox.Items.Count - 1)

            Dim myString As String = listBox.Items.IndexOf(i).ToString
            Dim mySubstring As String = Microsoft.VisualBasic.Right(myString, 4)
            comboBox.Items.Add(mySubstring)

        Next i

Is supposed to take the last four letters of each item in the list box, and then put those four letters into a combo box. However, when it comes down to it, it'll run and then when I look what's in the combo box, I get '-1'.

Where did that come from??

EDIT: or better still, does anyone know how to take a substring after a certain character, for example a . or a £? Had a look-see and can't find a thing lol.

Anyone know how I can get around it? Thanks in advance :)
 
Last edited:
Erm VB or VB.NET?

I guess .net other wise I think the loop should be :
For i = 0 To listBox.ListCount - 1
...
Next i

If Vb.NET:

You're getting -1 because indexOf() returns the position of an item in the listbox1.items collection.
You passed it a number on each loop and it couldn't find an item in the listbox which matched that number. ie. 1st loop it was looking through the entire collection for an item "1" which is not what you wanted.

You could have used ListBox1.Items(i).ToString for the same result.


For vb.net you can use
Code:
Dim ItemStr As String = ""
        For Each listObj As Object In ListBox1.Items()
            ItemStr = listObj.ToString
            If ItemStr.Length > 4 Then
                ComboBox1.Items.Add(ItemStr.Substring(ItemStr.Length - 4, 4))
                'ComboBox1.Items.Add(ItemStr.Substring(ItemStr.LastIndexOf(".")))
            Else
                ComboBox1.Items.Add(ItemStr)
            End If
        Next

The commented out line allows you to find the last instance of the character "." and use all the following charaters in the combobox.
 
Last edited:
Back
Top Bottom