【问题标题】:Listbox Sorting Issue列表框排序问题
【发布时间】:2015-07-11 09:16:26
【问题描述】:

即使使用 sorted = true 属性,我也无法按照我期望的方式对列表框进行排序。假设我有这样命名的文件,当我在 Windows 文件夹视图(vb 之外)中按“名称”排序时,它的排序如下:

1180741
1179715
1162371
1141511
1131750
1117362
1104199
1082698
1062921
1043875
991514
970621
963154
952954
948067
917669
904315
899902
892398
882024

这就是我需要它在我的列表中排序的方式。然而,使用 sorted = true 属性,vb.net 决定这样排序:

1043875
1062921
1082698
1104199
1117362
1131750
1141511
1162371
1179715
1180741
882024
892398
899902
904315
917669
948067
952954
963154
970621
991514

我不明白为什么 Windows 会正确排序列表,而 VB 却没有。任何帮助将不胜感激。

【问题讨论】:

  • 您的代码正在对其中包含字符串的 ListBox 进行排序(显然)。因此,正在应用字母/文本排序。 9 总是大于 1 或 10 或 11

标签: vb.net sorting listbox


【解决方案1】:

*这个例子假设列表框中的每个对象都是一个整数的字符串表示,如果不是,则该项目将被跳过,你可以修改它以另一种方式处理这种情况,如果你想要....

示例:

Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
    Dim r As New Random(Now.Millisecond)
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'We simulated a populated listbox
        For I As Integer = 0 To 1000
            Dim n As Integer = r.Next(0, Integer.MaxValue)
            ListBox1.Items.Add(n.ToString)
        Next
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        SortListBoxNumbers(ListBox1)
    End Sub
    Sub SortListBoxNumbers(listbox As ListBox)
        Dim numbers As New List(Of Integer)
        For Each item As Object In listbox.Items
            Dim n As Integer = 0
            If item.GetType = GetType(String) Then
                If Integer.TryParse(DirectCast(item, String), n) Then
                    numbers.Add(n)
                End If
            End If
        Next
        listbox.Items.Clear()
        numbers = SortNumbers(numbers)
        For Each n As Integer In numbers
            listbox.Items.Add(n.ToString)
        Next
    End Sub
    Function SortNumbers(numbers As List(Of Integer)) As List(Of Integer)
        Dim result As New List(Of Integer)
        Dim count As Integer = numbers.Count
        Do
            Dim highN As Integer = Integer.MinValue
            For Each n As Integer In numbers
                If n > highN Then highN = n
            Next
            numbers.Remove(highN)
            result.Insert(result.Count, highN)
        Loop Until result.Count = count
        result.Reverse()
        Return result
    End Function
End Class

【讨论】:

    猜你喜欢
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    相关资源
    最近更新 更多