Reordering items in BindingList in C#?
Asked Answered
F

2

6

How would I move items in a BindingList in C#? Say, move last added item to the front, or swap with previous item?

Fortissimo answered 18/4, 2009 at 18:47 Comment(1)
InsertItem method is something you should read about. I guess it gives you what you need.Wadmal
J
3

A BindingList has an Items property that implements IList<>

So you can Use Insert() and RemoveAt()

Joke answered 18/4, 2009 at 18:55 Comment(1)
yes, thank you :) just started learning c#, couldn't figure it out -- asked, and suddenly figured if out and came close the question :)Fortissimo
W
5
    static void Main(string[] args)
    {
        BindingList<string> list = new BindingList<string>();
        list.Add("Hello");
        list.Add("World");
        list.Add("Test");

        MoveLastToFirst(list);

        Swap(list, 1, 2);

        foreach (string s in list)
            Console.WriteLine(s); // Prints Test World Hello
    }

    private static void MoveLastToFirst<T>(BindingList<T> list)
    {
        int cnt = list.Count;
        T temp = list[cnt - 1];
        list.RemoveAt(cnt - 1);
        list.Insert(0, temp);
    }

    private static void Swap<T>(BindingList<T> list, int first, int second)
    {
        T temp = list[first];
        list[first] = list[second];
        list[second] = temp;
    }
Weiler answered 18/4, 2009 at 19:4 Comment(1)
Is there a way to reorder the BindingList using a comparator? There is no Sort method exposed on BindingList. There is ApplySortCore but it's protected, not public.Hypnology
J
3

A BindingList has an Items property that implements IList<>

So you can Use Insert() and RemoveAt()

Joke answered 18/4, 2009 at 18:55 Comment(1)
yes, thank you :) just started learning c#, couldn't figure it out -- asked, and suddenly figured if out and came close the question :)Fortissimo

© 2022 - 2024 — McMap. All rights reserved.