Move Up, Move Down Buttons for ListBoxes in Visual Studio [duplicate]

半城伤御伤魂 提交于 2019-12-06 03:34:44

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;

    }
}

You are looking for ListBox.Items.Add()

For the move-up, something like this should work:

void MoveUp()
{
    if (listBox1.SelectedItem == null)
        return;

    var idx = listBox1.SelectedIndex;
    var elem = listBox1.SelectedItem;
    listBox1.Items.RemoveAt(idx);
    listBox1.Items.Insert(idx - 1, elem);
}

for move down, just change idx - 1 to idx + 1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!