MoveListboxItem - Moving an item of a listbox to another index
' Moves an item of a listbox to another index
' If FROMINDEX = -1 then it moves the current highlighted item
'
' Example:
' ' move up the selected item
' MoveListboxItem(ListBox1, -1, ListBox1.SelectedIndex - 1)
' ' move down the selected item
' MoveListboxItem(ListBox1, -1, ListBox1.SelectedIndex + 1)
Sub MoveListboxItem(ByVal ctl As ListBox, ByVal fromIndex As Integer, _
ByVal toIndex As Integer)
If fromIndex = toIndex Then Exit Sub
' provide a default
If fromIndex < 0 Then fromIndex = ctl.SelectedIndex
' exit if argument not in range
If toIndex < 0 Or toIndex > ctl.Items.Count - 1 Then Exit Sub
With ctl
' save the data of the current item
Dim data As Object = .Items(fromIndex)
' remove the item
.Items.RemoveAt(fromIndex)
' add the item
.Items.Insert(toIndex, data)
' select the new item
.SelectedIndex = toIndex
End With
End Sub