Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Events for adding/removing items in a listbox c#.NET

I have a listbox control that has items dynamically added to and manually removed from (due to 'remove item' button). When the number of items is changed, I would like to update other parts of the user interface - namely a caption that says 'You must choose some files.' and an item count caption.

How can an event handler or effectively an event handler be added to fire when the number of items is changed - e.g. an ItemAdded or ItemRemoved or ItemsChanged

Note: This is nothing to do with the user selecting items in the listbox.

Thanks very much!

like image 915
James Avatar asked Oct 22 '11 15:10

James


Video Answer


2 Answers

You can try using a BindingList<> as your DataSource, and then you act on that list instead of your ListBox-- it will get the updates automatically from the BindingList.

The BindingList has a ListChanged event.

The ListChanged event has a ListChangedEventArgs that includes a ListChangedType enumerator:

BindingList<string> list = new BindingList<string>();
list.ListChanged += new ListChangedEventHandler(list_ListChanged);

void list_ListChanged(object sender, ListChangedEventArgs e) {
  switch (e.ListChangedType){
    case ListChangedType.ItemAdded:
      break;
    case ListChangedType.ItemChanged:
      break;
    case ListChangedType.ItemDeleted:
      break;
    case ListChangedType.ItemMoved:
      break;
    // some more minor ones, etc.
  }
}
like image 104
LarsTech Avatar answered Sep 18 '22 01:09

LarsTech


In the code for the "Remove Item" button, also update the other parts of the UI. This doesn't have to violate coding principles; you can do something like this:

void UpdatePartsOfTheUI() {
    // Do something here
    if(myListBox.Items.Count == 0) {
        myLabel.Text = "You must choose some files!";
    } else {
        myLabel.Text = String.Empty;
    }
}

/* ... */

void myButton_Click(object sender, EventArgs e) {
    if(myListBox.SelectedIndex > -1) {
        // Remove the item
        myListBox.Items.RemoveAt(myListBox.SelectedIndex);

        // Update the UI
        UpdatePartsOfTheUI();
    }
}

This works if you don't have many buttons that change the ListBox. If you do, just wrap the ListBox's Items.Add/Items.Insert/Items.Remove in methods that include your other code and call those from your button handlers instead.

like image 31
Ry- Avatar answered Sep 19 '22 01:09

Ry-