65.9K
CodeProject is changing. Read more.
Home

Moving listbox items

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.71/5 (11 votes)

Mar 26, 2008

CPOL
viewsIcon

68180

downloadIcon

1738

Move lisbox items and change indices.

Introduction

This solution helps with a small but sometimes irritating problem, which may cause time loss when working on large projects. It moves listbox items up and down on the click of a button.

Using the code

First off, add a button or two, depending on what you want to achieve, to your form and set this code to the up button action:

if (listBox1.SelectedItems.Count > 0)
{
    object selected = listBox1.SelectedItem;
    int indx = listBox1.Items.IndexOf(selected);
    int totl = listBox1.Items.Count;

    if (indx == 0)
    {
        listBox1.Items.Remove(selected);
        listBox1.Items.Insert(totl - 1, selected);
        listBox1.SetSelected(totl - 1, true);
    }
    else{
        listBox1.Items.Remove(selected);
        listBox1.Items.Insert(indx - 1, selected);
        listBox1.SetSelected(indx - 1, true);
    }
}

And then, add this to the down button action:

if (listBox1.SelectedItems.Count > 0)
{
    object selected = listBox1.SelectedItem;
    int indx = listBox1.Items.IndexOf(selected);
    int totl = listBox1.Items.Count;

    if (indx == totl - 1)
    {
        listBox1.Items.Remove(selected);
        listBox1.Items.Insert(0, selected);
        listBox1.SetSelected(0, true);
    }
    else{
        listBox1.Items.Remove(selected);
        listBox1.Items.Insert(indx + 1, selected);
        listBox1.SetSelected(indx + 1, true);
    }
}

Points of Interest

For even better usability, the buttons can be disabled by default, and can be enabled when an item is selected. Furthermore, I hope this code will come in handy!

Moving listbox items - CodeProject