Feedback

C# - Einträge in ListView verschieben

Veröffentlicht von am 5/10/2008
(1 Bewertungen)
Mit dieser Funktion lassen sich Einträge in einer ListView nach oben oder unten verschieben.
(Um eine Extension-Method zu erhalten muss einfach das Schlüsselwort "this" vor dem ersten Funktionsparameter eingefügt werden --> ... void MoveListViewItems(this ListView listView, ...)
/// <summary>
/// Moving direction for selected ListView entries
/// </summary>
public enum Direction
{
    /// <summary>
    /// Move ListView entries upwards.
    /// </summary>
    Up,
    /// <summary>
    /// Move ListView entries downwards.
    /// </summary>
    Down
}

/// <summary>
/// Move a the selected items in a ListView box in a specified direction.
/// </summary>
/// <param name="listView">The ListView.</param>
/// <param name="direction">The direction.</param>
public static void MoveListViewItems(ListView listView, Direction direction)
{
    List<ListViewItem> selectedItems = new List<ListViewItem>();

    foreach (ListViewItem lvItem in listView.SelectedItems)
    {
        selectedItems.Add(lvItem);
    }

    MoveListViewItems(listView, selectedItems, direction);
}

/// <summary>
/// Move a given list of ListView entries in a ListView box in a specified direction.
/// </summary>
/// <param name="listView">The ListView.</param>
/// <param name="listViewItems">The ListView items, which will be moved.</param>
/// <param name="direction">The direction.</param>
public static void MoveListViewItems(ListView listView, IEnumerable<ListViewItem> listViewItems, Direction direction)
{
    List<ListViewItem> items = new List<ListViewItem>(listViewItems);
    if (direction == Direction.Down)
    {
        for (int i = items.Count - 1; i >= 0 ; i--)
	    {
            ListViewItem lvItem = items[i];

            int oldIndex = lvItem.Index;
            int newIndex;

            listView.Items.Remove(lvItem);

		    if (oldIndex == listView.Items.Count)
            {
                newIndex = 0;
            }
            else
            {
                newIndex = oldIndex + 1;
            } 

            listView.Items.Insert(newIndex, lvItem);
	    }
    }
    else
    {
        foreach (ListViewItem lvItem in items)
        {
            int oldIndex = lvItem.Index;
            int newIndex;

            listView.Items.Remove(lvItem);

            if (oldIndex == 0)
            {
                newIndex = listView.Items.Count;
            }
            else
            {
                newIndex = oldIndex - 1;
            }

            listView.Items.Insert(newIndex, lvItem);
        }
    }
}

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!