Share via


How to sort numbers on a listbox

Question

Sunday, January 4, 2015 8:34 PM

Hey guys, 

I have a listbox with 15 numbers and i need them to be placed in ascending order.

But if i try :

Listbox3.sorted = true 

i receive this : 

1

10

11

2

20

27

.........

and i need this : 1-2-10-11-20-27

How can i do this ??????

All replies (6)

Sunday, January 4, 2015 9:25 PM ✅Answered

The ListBox.Sorted property causes the items to get sorted alphabetically as strings.

If you want to sort the items as integers you need to do the sorting yourself. You should sort the source collection. Here is an example that creates an integer array, sort it using the Array.Sort method and then use the AddRange method to add the integers to the ListBox:

        Dim arr(ListBox1.Items.Count - 1) As Integer
        For i As Integer = 0 To ListBox1.Items.Count - 1
            arr(i) = ListBox1.Items(i)
        Next
        Array.Sort(arr)
        ListBox1.Sorted = False
        ListBox1.Items.Clear()
        ListBox1.Items.AddRange(arr.Cast(Of Object).ToArray()) 

Please remember to mark helpful posts as answer and/or helpful.


Sunday, January 4, 2015 10:20 PM ✅Answered

Putting the data into a List() object makes it easy to sort.  See code below

Public Class Form1
    Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        Dim input As List(Of Integer) = New List(Of Integer)({1, 10, 11, 2, 20, 27})

        input.Sort()

        ListBox1.DataSource = input

    End Sub
End Class

jdweng


Monday, January 5, 2015 12:55 AM ✅Answered

Hello,

Here is one method using Lambda, first convert the items to integers then sort then as integers followed by adding them back into the ListBox, first we clear the current items

Dim SortedItems = ListBox3.Items.Cast(Of String)().ToList _
            .ConvertAll(Function(s) Integer.Parse(s)) _
            .ToArray.OrderBy(Function(x) x).ToArray
ListBox3.Items.Clear()
SortedItems.ToList.ForEach(Sub(s) ListBox3.Items.Add(s))

For completeness one would think without understanding the code that we could bypass ConvertAll but we need this as we need to convert and not use use OrderBy

Does not work

Dim SortedItems = ListBox3.Items.Cast(Of String)().ToArray.OrderBy(Function(x) x).ToArray
ListBox1.Items.Clear()
SortedItems.ToList.ForEach(Sub(s) ListBox3.Items.Add(s))

Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.


Monday, January 5, 2015 1:17 AM ✅Answered

.

Option Strict On

Public Class Form1

    Dim AscendingListBox As New List(Of Integer)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Left = 100
        Me.Top = 40
        ListBox1.Sorted = False
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If TextBox1.Text <> "" Then
            If IsNumeric(TextBox1.Text) Then
                Dim ItemToAdd As Integer
                If Integer.TryParse(TextBox1.Text, ItemToAdd) Then
                    ListBox1.Items.Add(ItemToAdd)
                    TextBox1.Clear()
                Else
                    MessageBox.Show("Please enter numerals only into the TextBox." & vbCrLf & _
                                    "This " & TextBox1.Text & " is not accepatable. Try again.")
                    TextBox1.Clear()
                End If
            Else
                TextBox1.Clear()
                MessageBox.Show("Please enter numerals only into the TextBox. Try again.")
            End If
        Else
            MessageBox.Show("Please enter one or more numerals into the TextBox.")
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If ListBox1.Items.Count > 1 Then
            AscendingListBox.Clear()
            For i = 0 To ListBox1.Items.Count - 1
                AscendingListBox.Add(CInt(ListBox1.Items(i)))
            Next
            AscendingListBox.Sort()
            ListBox1.Items.Clear()
            For i = 0 To AscendingListBox.Count - 1
                ListBox1.Items.Add(AscendingListBox(i))
            Next
        End If
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        ListBox1.Items.Clear()
    End Sub

End Class

La vida loca


Monday, January 5, 2015 2:14 AM ✅Answered

Yet another way:

Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'simulate 'recieved' numbers in an array
        Dim rec As Integer() = {1, 10, 11, 2, 20, 27}
        'convert the array to a list
        Dim recieved As List(Of Integer) = rec.ToList
        'iterate through the results after calling sortnumbers function, using recieved as a parameter
        For Each n As Integer In SortNumbers(recieved)
            'add each element to the listbox
            ListBox1.Items.Add(n)
        Next
    End Sub
    ''' <summary>
    ''' Sorts a list of integers
    ''' </summary>
    ''' <param name="numbers">The list of integers to be sorted</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Function SortNumbers(numbers As List(Of Integer)) As List(Of Integer)
        'store the sorted numbers here
        Dim result As New List(Of Integer)
        'get this number before it changes from removing items
        Dim count As Integer = numbers.Count
        'start a loop
        Do
            'set the highest value to the minimum value that way the next number is
            'guarenteed to be higher, or at least equal
            Dim highN As Integer = Integer.MinValue
            'go through each number remaining in the array(eventually this array will be empty)
            For Each n As Integer In numbers
                'find the highest number in the array
                If n > highN Then highN = n
            Next
            'remove the highest number from the array
            numbers.Remove(highN)
            'insert the highest number before the last number in the results array
            result.Insert(result.Count, highN)
            'loop again, or exit the loop if all items are in the results
        Loop Until result.Count = count
        'reverse the order of the results
        result.Reverse()
        'return the results
        Return result
    End Function
End Class

“If you want something you've never had, you need to do something you've never done.”

Don't forget to mark helpful posts and answers ! Answer an interesting question? Write a new article about it! My Articles

*This post does not reflect the opinion of Microsoft, or its employees.


Sunday, January 4, 2015 8:56 PM

Place all the numbers into a List(Of Integer).

Use sort to sort the integers into ascending order.

After the sort you could use reverse to reverse that so the integers are in descending order. Then revers again so they are in ascending order.

For whichever you do then add each item in the List(Of Integers) to the ListBox. Don't set ListBox.Sorted to true.

Dim ListBoxIntegers As New List(Of Integer) ' Global instantiation

In some event handler

ListBoxIntegers.Add(10) ' Add one integer at a time unless you have an array of integers then use AddRange

After adding all integers.

ListBox1Integers.Sort

In some event handler

ListBox1.Items.Clear()

For Each Item in ListBoxIntegers

ListBox1.Items.Add(Item.ToString)

Next

La vida loca