简体   繁体   中英

keeping only 5 items in a listbox

I want to create a simple listbox, which is binded to a linkedlist. The list should only ever hold 5 items at any given time. When a new item is added, it should check if item count >= 5 and then remove the last item and add the new item to the top.

To do this, I made this test app:

public partial class Form1 : Form
{
    LinkedList<string> list01 = new LinkedList<string>();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        list01.AddFirst("AAA");
        list01.AddFirst("BBB");
        list01.AddFirst("CCC");

        listBox1.DataSource = new BindingSource(list01, "");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (list01.Count >= 5)
            list01.RemoveLast();

        list01.AddFirst(DateTime.Now.ToString());
        listBox1.DataSource = new BindingSource(list01, "");
    }
}

It appears, when ever I add a new item, I have to keep setting the datasource to a new bindingsource for the added item to show on the UI

Is there way to initisalise one binding source, and when the items in it changes, auto update the listbox without having to set the datasource every time you add a new item?

You need a collection which implements collection changed notification. There are two options you have BindingList<T> and ObservableCollection<T> .

Pick any one, From your comment it seems you're just looking for AddFirst and RemoveLast . You can create a extension method yourself which does that.

public static class BindingListExtension
{
    public static void AddFirst<T>(this BindingList<T> list, T item)
    {
        list.Insert(0, item);
    }

    public static void RemoveLast<T>(this BindingList<T> list)
    {
        list.RemoveAt(list.Count - 1);
    }
}

Based on Sriram Sakthivel's suggestion, I have achieved my requirement like this:

public partial class Form1 : Form
{
    BindingList<string> list01 = new BindingList<string>();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        listBox1.DataSource = list01;

        list01.Add("AAA");
        list01.Add("BBB");
        list01.Add("CCC");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (list01.Count >= 5)
            list01.RemoveAt(4);

        list01.Insert(0, DateTime.Now.ToString());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM