I have a listbox control that has item
s 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!
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.
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With