views:

151

answers:

1

I have seemingly simple problem in Winforms.

I want to implement a collection that can be used as a DataSource for a listbox. I intend to use it for simple strings. Like so:

MyBindingCollection<string> collection = new MyBindingCollection<string>();
listbox.DataSource = collection;

I've read that all I need to implement is IList interface. However I would like the listbox to update itself when I do:

collection.Add('test');
collection.RemoveAt(0):

How do I create such collection? This is only one-way binding, I do not need to update collection from the GUI. (listbox is read only).

+1  A: 

Try using BindingList<T> it works for both one way and bidirectional binding.

BindingList<string> list = new BindingList<string>();
listbox.DataSource = list;

list.Add("Test1");
list.Add("Test2");
list.RemoveAt(0);

Edit:
Added a sample solution with IBindingList
You don´t have to implement all the methods for the IBindingList interface.
The ones you don´t need just throw an NotImplementedException.

public class MyBindingList : IBindingList
{
    private readonly List<string> _internalList = new List<string>();

    public int Add(object value)
    {
        _internalList.Add(value.ToString());
        var listChanged = ListChanged;
        var newIndex = _internalList.Count - 1;
        if (listChanged != null)
        {
            listChanged(this, new ListChangedEventArgs(ListChangedType.ItemAdded, newIndex));
        }
        return newIndex;
    }

    public event ListChangedEventHandler ListChanged;

    public int IndexOf(object value) // No need for this method
    {
        throw new NotImplementedException();
    }

    // + all other methods on IBindingList interface
}
Jens Granlund
The thing is I have specific needs for this collection and want to implement the internals my self. So BindingList is probably out of question.
Kugel
@Kugel, then you can create your own class and inherit from BindingList<T> or implement IBindingList.
Jens Granlund
@Kugel, the event that is updating the listBox is the IBindingList.ListChanged Event, so if your collection is implementing IBindingList, that is about all you need to implement. Every thing else you can just throw NotImplementedException.
Jens Granlund