Sub MoveSelectedItemUp(ByVal Box As ListBox)
Dim Index As Integer = Box.SelectedIndex 'Index of selected item
Dim Swap As Object = Box.SelectedItem 'Selected Item
If Not (Swap Is Nothing) Then 'If something is selected...
Box.Items.RemoveAt(Index) 'Remove it
Box.Items.Insert(Index - 1, Swap) 'Add it back in one spot up
Box.SelectedItem = Swap 'Keep this item selected
End If
End Sub
void MoveSelectedItemUp(ListBox Box) {
int Index = Box.SelectedIndex; //Selected Index
object Swap = Box.SelectedItem; //Selected Item
If (Index == -1) { //If something is selected...
Box.Items.RemoveAt(Index); //Remove it
Box.Items.Insert(Index - 1, Swap); //Add it back in one spot up
Box.SelectedItem = Swap; //Keep this item selected
}
}
Sub MoveSelectedItemDown(ByVal Box As ListBox)
Dim Index As Integer = Box.SelectedIndex 'Index of selected item
Dim Swap As Object = Box.SelectedItem 'Selected Item
If (Index <> -1) AndAlso (Index + 1 < Box.Items.Count) Then
Box.Items.RemoveAt(Index) 'Remove it
Box.Items.Insert(Index + 1, Swap) 'Add it back in one spot up
Box.SelectedItem = Swap 'Keep this item selected
End If
End Sub
private void MoveListboxItem(int index, ListBox listBox)
{
if (listBox.SelectedIndex != -1) //is there an item selected?
{
//if it's moving up, the loop moves from first to last, otherwise, it moves from last to first
for (int i = (index < 0 ? 0 : listBox.Items.Count - 1); index < 0 ? i < listBox.Items.Count : i > -1; i -= index)
{
if (listBox.Items[i].Selected)
{
//if it's moving up, it should not be the first item, or, if it's moving down, it should not be the last
if ((index < 0 && i > 0) || (index > 0 && i < listBox.Items.Count - 1))
{
//if it's moving up, the previous item should not be selected, or, if it's moving down, the following item should not be selected
if ((index < 0 && !listBox.Items[i - 1].Selected) || (index > 0 && !listBox.Items[i + 1].Selected))
{
ListItem itemA = listBox.Items[i]; //the selected item
listBox.Items.Remove(itemA); //is removed
listBox.Items.Insert(i + index, itemA);//and swapped
}
}
}
}
}
}