Move Up, Move Down Buttons for ListBoxes in Visual Studio

Cindy picture Cindy · Apr 1, 2013 · Viewed 12.4k times · Source

I am trying to make a Move Up Button, and a Move Down Button, to move a selected item in a ListBox in Microsoft Visual Studio 2012. I have seen other examples in WDF, jquery, winforms, and some other forms but I haven't seen examples from Microsoft Visual Studio yet.

I have tried something like this:

        listBox1.AddItem(listBox1.Text, listBox1.ListIndex - 1);

But Microsoft Visual Studio didn't have an "AddItem" property in their ListBoxes.

For more information, I have two listboxes that I want to make my Move up and down Buttons work with; the SelectedPlayersListBox, and the AvailablePlayersListBox. Will someone be kind enough to give me examples of a Move Up and Down button in Microsoft Visual Studio? Thank you.

Answer

djv picture djv · Apr 2, 2013

Sarcasm-free answer. Enjoy

private void btnUp_Click(object sender, EventArgs e)
{
    MoveUp(ListBox1);
}

private void btnDown_Click(object sender, EventArgs e)
{
    MoveDown(ListBox1);
}

void MoveUp(ListBox myListBox)
{
    int selectedIndex = myListBox.SelectedIndex;
    if (selectedIndex > 0)
    {
        myListBox.Items.Insert(selectedIndex - 1, myListBox.Items[selectedIndex]);
        myListBox.Items.RemoveAt(selectedIndex + 1);
        myListBox.SelectedIndex = selectedIndex - 1;
    }
}

void MoveDown(ListBox myListBox)
{
    int selectedIndex = myListBox.SelectedIndex;
    if (selectedIndex < myListBox.Items.Count - 1 & selectedIndex != -1)
    {
        myListBox.Items.Insert(selectedIndex + 2, myListBox.Items[selectedIndex]);
        myListBox.Items.RemoveAt(selectedIndex);
        myListBox.SelectedIndex = selectedIndex + 1;

    }
}