Sorting Listbox Items numerically in VB

2019-01-20 00:58发布

I need to sort the items in a visual basic listbox numerically, that is, I have a collection of numbers I would like to be sorted increasingly.

I tried to simply use the listbox's Sorted property, but found that it treated the numbers as if they were strings, that is, it would look at the first digit, then the second, etc. to determine the order. That meant that 13 would show before 5, for example.

I thought of dumping all the numbers into an array, soring the array, and then pushing them back to the listbox, but, honestly, I don't know how to go about the sorting. I figured the array would be useless, since the listbox already acts as a pseudo array.

Any ideas?

2条回答
可以哭但决不认输i
2楼-- · 2019-01-20 01:24

You could dump the items into a List(Of Integer) object and call its sort. Then bind your listbox to that new list post-sort.

查看更多
贼婆χ
3楼-- · 2019-01-20 01:26

You can use something like this:

Private Shared Sub SortIntegerListBox(ByVal listBox As ListBox)
    Dim TempList As New List(Of Integer)
    For Each LI In listBox.Items
        TempList.Add(Integer.Parse(LI.ToString()))
    Next
    TempList.Sort()
    listBox.DataSource = TempList
End Sub

And call it after binding:

    Dim Items As New List(Of Integer)
    Items.Add(1)
    Items.Add(13)
    Items.Add(2)

    Me.ListBox1.DataSource = Items
    SortIntegerListBox(Me.ListBox1)
查看更多
登录 后发表回答