How to move item in listBox up and down?

user586399 picture user586399 · Jan 25, 2011 · Viewed 74k times · Source

I have a listBox1 object and it contains some items. I have a button to move selected item up and another to move selected item down. What should the code be to the two buttons?

Answer

Save picture Save · Mar 13, 2012
 public void MoveUp()
 {
     MoveItem(-1);
 }

 public void MoveDown()
 {
    MoveItem(1);
 }

 public void MoveItem(int direction)
 {
    // Checking selected item
    if (listBox1.SelectedItem == null || listBox1.SelectedIndex < 0)
        return; // No selected item - nothing to do

    // Calculate new index using move direction
    int newIndex = listBox1.SelectedIndex + direction;

    // Checking bounds of the range
    if (newIndex < 0 || newIndex >= listBox1.Items.Count)
        return; // Index out of range - nothing to do

    object selected = listBox1.SelectedItem;

    // Removing removable element
    listBox1.Items.Remove(selected);
    // Insert it in new position
    listBox1.Items.Insert(newIndex, selected);
    // Restore selection
    listBox1.SetSelected(newIndex, true);
}

UPD 2020-03-24: Extension class for simple reuse and it also supports CheckedListBox (if CheckedListBox is not needed for you, please remove appropriate lines of code). Thanks @dognose and @Chad

public static class ListBoxExtension
{
    public static void MoveSelectedItemUp(this ListBox listBox)
    {
        _MoveSelectedItem(listBox, -1);
    }

    public static void MoveSelectedItemDown(this ListBox listBox)
    {
        _MoveSelectedItem(listBox, 1);
    }

    static void _MoveSelectedItem(ListBox listBox, int direction)
    {
        // Checking selected item
        if (listBox.SelectedItem == null || listBox.SelectedIndex < 0)
            return; // No selected item - nothing to do

        // Calculate new index using move direction
        int newIndex = listBox.SelectedIndex + direction;

        // Checking bounds of the range
        if (newIndex < 0 || newIndex >= listBox.Items.Count)
            return; // Index out of range - nothing to do

        object selected = listBox.SelectedItem;

        // Save checked state if it is applicable
        var checkedListBox = listBox as CheckedListBox;
        var checkState = CheckState.Unchecked;
        if (checkedListBox != null)
            checkState = checkedListBox.GetItemCheckState(checkedListBox.SelectedIndex);

        // Removing removable element
        listBox.Items.Remove(selected);
        // Insert it in new position
        listBox.Items.Insert(newIndex, selected);
        // Restore selection
        listBox.SetSelected(newIndex, true);

        // Restore checked state if it is applicable
        if (checkedListBox != null)
            checkedListBox.SetItemCheckState(newIndex, checkState);
    }
}