sorting listbox by word length question

genialus

New member
Joined
Nov 4, 2006
Messages
1
Programming Experience
Beginner
Hi, as in the headline, what i'm trying to do is make a function that sorts all the items of a listbox ordered by the length of the words.

so is there someone out there who can help me ?

best regards
Genialus
 
You can do as suggested in the documentation for the Listbox.Sort method and inherit a Listbox and override its protected Sort method, but it is more common and versatile to sort the items prior to adding them to the Listbox. Here is an example, used is a List(Of String) and custom sorted by an implementation of the IComparer(Of String).
VB.NET:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
  Dim los As New List(Of String)
  los.Add("long string")
  los.Add("short")
  los.Add("medium")
  los.Sort(New StringLengthComparer)
  ListBox1.DataSource = los
End Sub
 
Class StringLengthComparer
Implements IComparer(Of String)
  Public Function Compare(ByVal x As String, ByVal y As String) As Integer _
  Implements System.Collections.Generic.IComparer(Of String).Compare
    Return x.Length - y.Length
  End Function
End Class
 
Back
Top