Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reordering items in BindingList in C#?

Tags:

c#

bindinglist

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

like image 531
flamey Avatar asked Apr 18 '09 18:04

flamey


2 Answers

    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;
    }
like image 83
Jason Kresowaty Avatar answered Sep 20 '22 19:09

Jason Kresowaty


A BindingList has an Items property that implements IList<>

So you can Use Insert() and RemoveAt()

like image 22
Henk Holterman Avatar answered Sep 17 '22 19:09

Henk Holterman