Как переместить элемент в списке вверх и вниз? - PullRequest
29 голосов
/ 25 января 2011

У меня есть объект listBox1, и он содержит некоторые элементы.У меня есть кнопка для перемещения выбранного элемента вверх, а другая - для перемещения выбранного элемента вниз.Каким должен быть код для двух кнопок?

Ответы [ 15 ]

1 голос
/ 13 июня 2014
// Options is a list box

private void MoveUpButton_Click(object sender,EventArgs e) {                            
    int index = Options.SelectedIndex;                                          
    if (index <= 0) return;
    string item = (string)Options.Items[index - 1];                         
    Options.Items.RemoveAt(index - 1);                                                                              
    Options.Items.Insert(index,item);                                           
    selectedIndexChanged(null,null);                                                                        
    }

private void MoveDnButton_Click(object sender,EventArgs e) {                            
    int index = Options.SelectedIndex;
    if (index + 1 >= Options.Items.Count) return;
    string item = (string)Options.Items[index];
    Options.Items.RemoveAt(index);
    Options.Items.Insert(index + 1,item);
    Options.SelectedIndex = index + 1;
    }

// sent when user makes a selection or when he moves an item up or down

private void selectedIndexChanged(object sender,EventArgs e) {
    int index = Selected.SelectedIndex;
    MoveUpButton.Enabled = index > 0;
    MoveDnButton.Enabled = index + 1 < Selected.Items.Count;
    }
0 голосов
/ 20 марта 2019

Для тех, кто ищет общий способ работы с ListBox, который может быть связан с источником данных, вот общее расширение, основанное на ответ Save * , который будет обрабатывать обычный и связанный ListBox.

public static void MoveUp(this ListBox listBox)
{
    listBox.MoveItem(-1);
}

public static void MoveDown(this ListBox listBox)
{
    listBox.MoveItem(1);
}

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

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

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


    //Find our if we're dealing with a BindingSource
    bool isBindingSource = listBox.DataSource is BindingSource;

    //Get the list
    System.Collections.IList list = isBindingSource ? ((BindingSource)listBox.DataSource).List : listBox.Items;

    object selected = listBox.SelectedItem;

    // Removing removable element
    list.Remove(selected);

    // Insert it in new position
    list.Insert(newIndex, selected);

    // Restore selection
    listBox.SetSelected(newIndex, true);

    if (isBindingSource)
    {
        //Reset the binding if needed
        ((BindingSource)listBox.DataSource).ResetBindings(false);
    }

}
0 голосов
/ 13 октября 2016

Я использую это с несколькими вариантами выбора. Он также работает с чередованными выделениями.

        private void Order_buttons_Click(object sender, EventArgs e)
    {
        //If noselection return
        if (Layouts_listBox.SelectedItems.Count == 0) return;

        //Determines wether up or down
        int movement = (sender as Button) == Order_Upbutton? - 1 : 1;

        //creates a dictionary associating the original Index (ListBox) to the text
        Dictionary<int, string> Items = new Dictionary<int, string>();

        //Also creates a list with the Index for sorting
        List<int> DesiredOrder = new List<int>();

        //Cycle through the selection and fill both the list and dictionary
        ListBox.SelectedObjectCollection NN = Layouts_listBox.SelectedItems;
        foreach (object n in NN)
        {
            DesiredOrder.Add(Layouts_listBox.Items.IndexOf(n));
            Items.Add(Layouts_listBox.Items.IndexOf(n), (string)n);
        }

        //Sort the List according to the desired button (Up or Down)
        DesiredOrder.Sort();
        if ((sender as Button) != Order_Upbutton) DesiredOrder.Reverse();

        //I'm using this ErrorHandling but thats up to you
        try
        {
            //Call the MoveItem (Credits to Save) according to the sorted order
            foreach (int n in DesiredOrder) MoveItem(movement, Items[n]);
        }
        catch (Exception)
        {
            SystemSounds.Asterisk.Play();
        }
    }
    public void MoveItem(int direction, string Selected)
    {
        // Checking selected item
        if (!Layouts_listBox.Items.Contains(Selected) || Layouts_listBox.Items.IndexOf(Selected) < 0)
            throw new System.Exception(); // No selected item - Cancel entire Func

        // Calculate new index using move direction
        int newIndex = Layouts_listBox.Items.IndexOf(Selected) + direction;

        // Checking bounds of the range
        if (newIndex < 0 || newIndex >= Layouts_listBox.Items.Count)
            throw new System.Exception(); // Index out of range - Cancel entire Func

        object selected = Layouts_listBox.Items[Layouts_listBox.Items.IndexOf(Selected)];

        // Removing removable element
        Layouts_listBox.Items.Remove(selected);
        // Insert it in new position
        Layouts_listBox.Items.Insert(newIndex, selected);
        // Restore selection
        Layouts_listBox.SetSelected(newIndex, true);
    }
0 голосов
/ 20 июня 2013

Для кнопки «Вверх»:

  private void UpBottom_Click(object sender, EventArgs e)
    {
        //this.Options is ListBox
        if (this.Options.SelectedIndex == -1 ||
             this.Options.SelectedIndex == 0)
            return;

        string item, aboveItem;
        int itemIndex, aboveItemIndex;
        itemIndex = this.Options.SelectedIndex;
        aboveItemIndex = this.Options.SelectedIndex - 1;
        item = (string)this.Options.Items[itemIndex];
        aboveItem = (string)this.Options.Items[aboveItemIndex];

        this.Options.Items.RemoveAt(aboveItemIndex);
        this.Options.Items.Insert(itemIndex, aboveItem);
    }

Для кнопки «Вниз»:

private void DownButton_Click(object sender, EventArgs e)
    {
        //this.Options is ListBox
        if (this.Options.SelectedIndex == -1 ||
                         this.Options.SelectedIndex >= this.Options.Items.Count)
            return;

        string item, belowItem;
        int itemIndex, belowItemIndex;
        itemIndex = this.Options.SelectedIndex;
        belowItemIndex = this.Options.SelectedIndex + 1;
        if (belowItemIndex >= this.Options.Items.Count)
            return;
        item = (string)this.Options.Items[itemIndex];
        belowItem = (string)this.Options.Items[belowItemIndex];

        this.Options.Items.RemoveAt(itemIndex);
        this.Options.Items.Insert(belowItemIndex, item);
        this.Options.SelectedIndex = belowItemIndex;
    }
0 голосов
/ 26 июля 2012

Я написал эту функцию для перемещения выбранных элементов:

using System.Collections;
using System.Collections.Generic;

private void MoveListboxItems(int step, ListBox lb) {
    /* 'step' should be:
     *   -1 for moving selected items up
     *    1 for moving selected items down
     * 'lb' is your ListBox
     *   see examples how to call below this function
    */
    try {
        // do only something when really an item is selected
        if (lb.SelectedIndex > -1) {
            // get some needed values - they change while we manipulate the listbox
            // but we need them as they was original
            IList SelectedItems = lb.SelectedItems;
            IList SelectedIndices = lb.SelectedIndices;

            // set some default values
            int selIndex = -1;
            int newIndex = -1;
            int selCount = SelectedItems.Count;
            int lc = 0;
            int mc = 0;
            string moveOldValue = string.Empty;
            string selectedItemValue = string.Empty;

            if (step == 1) {
                mc = selCount - 1;
            } else {
                mc = lc;
            }
            // enter the loop through the selected items
            while (lc < selCount) {
                selectedItemValue = string.Empty;
                moveOldValue = string.Empty;

                try {
                    // get the item that should get moved
                    selectedItemValue = SelectedItems[mc].ToString();
                    selIndex = Convert.ToInt32(SelectedIndices[mc]);
                } catch {
                    selIndex = -1;
                }
                // gen index for new place
                newIndex = selIndex + step;
                try {
                    // get the old value from the place where the item get moved
                    moveOldValue = lb.Items[newIndex].ToString();
                } catch { /* do nothing */ }
                try {
                    if (!String.IsNullOrEmpty(selectedItemValue) && !String.IsNullOrEmpty(moveOldValue) && selIndex != -1 && newIndex != -1 && !lb.SelectedIndices.Contains(newIndex)) {
                        // move selected item
                        lb.Items.RemoveAt(newIndex);
                        lb.Items.Insert(newIndex, selectedItemValue);
                        // write old value back to the old place from selected item
                        lb.Items.RemoveAt(selIndex);
                        lb.Items.Insert(selIndex, moveOldValue);
                        // hold the moved item selected
                        lb.SetSelected(newIndex, true);
                    }
                } catch { /* do nothing */ }
                lc++;
                if (step == 1) {
                    mc -= step;
                } else {
                    mc = lc;
                }
            }
        }
    } catch { /* do nothing */ };
}

// examples how i call the function above
void BtnLbUp_Click(object sender, EventArgs e) {
    MoveListboxItems(-1, this.lbMyList);
}

void BtnLbDown_Click(object sender, EventArgs e) {
    MoveListboxItems(1, this.lbMyList);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...