0
votes

i've created two buttons ('Move Top' and 'Move Bottom') and I have to make them work as follows. when I click an item from a ListBox (for example, if we have the items: 1. Cat, 2. Dog, 3. Bird, 4. Dinosaur and 5. Phoenix in the ListBox) it moves straight to the top or to the bottom.

Let's say I want to move the element Dinosaur to the top of my ListBox, and the element Dog - to the bottom. How can I make it work? Again - I should make it work by moving it directly to the top/bottom.

PS: It's my first day on here so excuse me if my question is not clear enough :)

4
What are you using ? WPF, WinForms, ASP.NET, ASP.MVCBobby Tables
I'm using Windows FormsAnton Grancharov
Possible duplicate of C# Move item in Listbox to the topSinatr

4 Answers

1
votes

If you want to insert an item in a ListBox at position 0 (start) you can use:

ListBox c = new ListBox();
string item="Some string";
c.Items.Insert(0, item); //added as first item in Listbox

if you want to insert it at the end of listbox use:

c.Items.Add(item); //add at the end
0
votes

Assuming you are using MVVM and binding an ObservableCollection to your ListBox.

You can get the index of the SelectedItem with IndexOf and use the Move method of ObservableCollection.

public void Move(int oldIndex, int newIndex)
0
votes

Do you want something similar to this?

       public void MoveUp()
    {
        MoveItem(-1);
    }

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

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

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

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

        object selected = yourListBox.SelectedItem;

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

This should do the trick.

public void MoveToTop(ListBox lb, int index) {
    var item = lb.Items[index];
    lb.Items.RemoveAt(index);
    lb.Items.Insert(0, item);
    lb.Refresh();
}

public void MoveToBottom(ListBox lb, int index) {
    var item = lb.Items[index];
    lb.Items.RemoveAt(index);
    lb.Items.Add(item);
    lb.Refresh();
}