0

I have two ListBoxes and I want to move items between them. The code looks like this:

    private void FillItems()
    {
        allItems = GetAllItems();
        availableItems = new List<string>(allItems);
        selectedItems = new List<string>();

        itemsListBox.DataSource = availableItems;
        selectedItemsListBox.DataSource = selectedItems;
    }

    private void addItemButton_Click(object sender, EventArgs e)
    {
        var itemsToAdd = itemsListBox.SelectedItems;
        foreach (string item in itemsToAdd)
        {
            availableItems.Remove(item);
            selectedItems.Add(item);
        }
    }

Simple enough. I move strings from one list into another.

Now this doesn't work, just as it shouldn't. I realise that it's missing some way of notifying about collection change. So I tried these options:

  1. Calling Refresh() on the list boxes. No avail.

  2. Using an extra layer of data binding (BindingSource). Also no avail.

  3. Calling ResetBindings() on the control. Still nothing.

What am I doing wrong here? Should I use some kind of an observable collection?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
John NoCookies
  • 1,041
  • 3
  • 17
  • 28

3 Answers3

2

If you import the System.ComponentModel namespace, then you can use a binding list of string, which will automatically raise events on changes:

private void FillItems()
{
    allItems = GetAllItems();
    availableItems = new BindingList<string>(allItems);
    selectedItems = new BindingList<string>();

    itemsListBox.DataSource = availableItems;
    selectedItemsListBox.DataSource = selectedItems;
}

private void addItemButton_Click(object sender, EventArgs e)
{
    object itemsToAdd = itemsListBox.SelectedItems;
    foreach (string item in itemsToAdd) {
        availableItems.Remove(item);
        selectedItems.Add(item);
    }
}

This link has further information on the difference between observable collections and binding lists. difference between ObservableCollection and BindingList

Community
  • 1
  • 1
OCDan
  • 1,103
  • 1
  • 10
  • 19
  • Worked. For posterity: I had to rewrite `SelectedItems` to a separate list because the collection changes, causing the `foreach` to crash. – John NoCookies Jul 05 '13 at 11:01
0

I prefer using ObservableCollections because you do not need to refresh binding yoursef, take a look

http://msdn.microsoft.com/en-us/library/ms668604.aspx

Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
0

You can also use BindingList

DIfference between BindingList and ObservableCollection explained here)

Community
  • 1
  • 1
Arie
  • 5,251
  • 2
  • 33
  • 54