Sorting Items in ListBox in VB.Net

Hi everybody,
  How would you sort items in a Listbox based on what is selected and move it up or down How to get its index of item if there is one, nad change the index of items by rearrnging them

  This to be done in VB.Net Windows Application. Thanks.

den2005



Answer this question

Sorting Items in ListBox in VB.Net

  • Schoene

    Button2 is an UP button, ListBox1 is the listbox to re-arrange. The code assumes that you are using the VB6 method for ItemData, otherwise you may delete Husk2 and lines with ItemData.

    Private Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click

    Dim Husk1 As String

    Dim Husk2, n As Integer

    With ListBox1

    If .Items.Count > 1 Then

    If .SelectedIndex > -1 Then

    If .SelectedIndex > 0 Then

    n = .SelectedIndex

    Husk1 = .GetItemText(.Items(n))

    Husk2 = VB6.GetItemData(ListBox1, n)

    .Items(n) = .GetItemText(.Items(n - 1))

    VB6.SetItemData(ListBox1, n, VB6.GetItemData(ListBox1, n - 1))

    .Items(n - 1) = Husk1

    VB6.SetItemData(ListBox1, n - 1, Husk2)

    .SetSelected(n - 1, True)

    End If

    End If

    End If

    End With

    End Sub


  • rranft

    Thanks cphtsu for eply. I would try it and let you know.

    den2005

  • Sorting Items in ListBox in VB.Net