I tried to fixed and figure out to move bottom and top for swap. it won't move.

private void topbutton_Click(object sender, EventArgs e)
        {
            int moveSpace = postProcesslistBox.SelectedIndex;
            int ItemIndexOfItemToMove = postProcesslistBox.SelectedIndex;

            if (this.postProcesslistBox.SelectedIndex != 0)
            {
                for (int i = ItemIndexOfItemToMove; i != 0; i--)
                {
                    Swap(i, i - 1);
                    this.postProcesslistBox.SelectedIndex = i-1;
                }
            }
        }

private void Swap(int a, int b)
        {
            int temp = a;
            a = b;
            b = temp;

        }

thanks

private void topbutton_Click(object sender, EventArgs e) {
    int ItemIndexOfItemToMove = postProcesslistBox.SelectedIndex;

    if (this.postProcesslistBox.SelectedIndex != 0) {
        for (int i = ItemIndexOfItemToMove; i != 0; i--) {
                object o = myListBox1.Items[i];
                myListBox1.Items.RemoveAt(i);
                myListBox1.Items.Insert(i-1, o);        }
    }
}

This code will move the selected item to the top. You can do it much faster just by using:

private void topbutton_Click(object sender, EventArgs e) {
    int i = postProcesslistBox.SelectedIndex;

    object o = myListBox1.Items[i];
    myListBox1.Items.RemoveAt(i);
    myListBox1.Items.Insert(0, o);
}

I took the error because I use to type postProcessList.Add("Item1") with any list, then postProcessListBox.DataSource = postProcessList. I can't move top button but it is error again.

I took your example, it is work but I work for DataSource and I read message error, it said Items Collection cannot be modified when the DataSource property is set. Let me know how do I work? Thanks.

Like it says, if you use a DataSource you can't modify the collection. You'll have to take the data from the DataSource and add it to the listbox yourself, rather than setting the DataSource property.

This article has been dead for over six months. Start a new discussion instead.