alphaprolix
alphaprolix

Reputation: 601

Want to execute code on listbox.items.clear()

I have a listbox and a checkbox(select all), In my code I'm calling listbox.items.clear(), now I want to subscribe to this event, so whenever my list box gets clear, the selectAll check box should also be in uncheck state.

Currently I am handling this in my listbox SelectedIndexChanged event, I could not find an ItemsClear kind of event in the list of my listbox events.

I would really like to uncheck my checkbox using event handling.

Upvotes: 0

Views: 567

Answers (4)

Larry
Larry

Reputation: 18031

If events are critical to you, I suggest to use a BindingList and bind the ListBox to, if your scenario allows it. This approach might give you some new ideas.

BindingList<string> myList;

myList = new BindingList<string>(...);
listBox1.DataSource = myList;
myList.ListChanged += new ListChangedEventHandler(myList_ListChanged);

Then, by using the ListChanged event of the BindingList (among many others), you can do the operation on your "Select all" checkbox when your ListBox is cleared by ListBox1.Items.Clear().

void myList_ListChanged(object sender, ListChangedEventArgs e)
{
    if (e.ListChangedType == ListChangedType.Reset)
    {
        ... // Do what you need here
    }
}

Upvotes: 2

User 12345678
User 12345678

Reputation: 7804

As far as I know there is no event that is raised as a direct result of ListBox.Items.Clear being called. You can implement your own behavior though:

public class CustomListBox : ListBox
{
    public event EventHandler ItemsCleared;

    public void ClearItems()
    {
        Items.Clear();
        if(this.ItemsCleared != null)
        {
            this.ItemsCleared(this, EventArgs.Empty);
        }
    }
}

Simply declare the class above in your Windows Forms Application. Instead of using the standard ListBox use your extended CustomListBox and subscribe to the ItemsCleared event.

Instead of calling CustomListBox.Items.Clear call CustomListBox.ClearItems

Upvotes: 2

Myrtle
Myrtle

Reputation: 5831

This sounds like a round-trip. When you call your Clear method, you know that you are clearing it in the code. React in code, there is no need for the round trip.

For example create a helper method that clears the listbox and then executes the code you want after clearing the listbox.

Upvotes: 4

bash.d
bash.d

Reputation: 13207

You are right, there is no event for this. But why be so complicated? Define yourself a method like

private void ClearAndUncheck(){
    listbox.Items.Clear();
    selectAll.Checked = false;
}

Upvotes: 2

Related Questions