Patryk
Patryk

Reputation: 3152

c#, is there OnChange event in ListBox?

I've been looking for something like that but I couldn't find it. I want my program to do something when there's any change in ListBox (e.g. changing selected item, adding new one, removing one and so on)

Upvotes: 6

Views: 21024

Answers (3)

NachFenix
NachFenix

Reputation: 11

just note, that´s not tottaly correct, best it´s once you change the content on the Listbox, do something like that additionally:

FilterListBox.SelectedIndex = FilterListBox.Items.Count-1;

In order to change the index, then you will be able to use the eventhandler for SelelectedIndexChanged. Thanks for your help!

Upvotes: 0

Davio
Davio

Reputation: 4737

If you're binding your ListBox to say a BindingList, you can use the BindingLists's ListChanged event. The ListChangedEventArgs has an argument ListChangedType which tells you if an item was added, removed, moved or changed.

You can do similar things with similar collections.

If you're adding or removing items yourself, you can obviously directly tell some other piece of code to execute or you can just create and raise an event yourself, provided you have a ListAdded event:

ListAdded(this, new ListAddedEventArgs() { List = myList, Item = myItem });

Upvotes: 4

user520288
user520288

Reputation:

You can use the SelectedIndexChanged or SelectedValueChanged events.

For adding or removing items there are no .NET events, so you have to implement that functionality yourself. This SO post explains how you can accomplish that.

Good luck!

PS: I assumed you are using Windows Forms

Upvotes: 8

Related Questions