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

2019-07-03 00:22发布

问题:

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!

回答1:

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.
  }
}


回答2:

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.



回答3:

Create a method to which you can do what you want with the ListBox Item. for example:

my program receives data feeds from a server upon request or request for stream. In my winform1.cs my control for adding data to a list box is as followed.

public void AddData(string data)
    {
        if (this.ResponseData.InvokeRequired)
            BeginInvoke(new AddDataDelegate(AddData), new object[] { data });
        else
        {
            this.ResponseData.Items.Insert(0, data);
            DataDistro();

        }

    }

DataDistro Is what I called My Method for doing work with the new data. Also Note by inserting at index value 0, the new item will Always be on top.

If you are using winForm this is a lot easier, Also, Because the adding of an item is handled by a delegate, the main thread is still open. If your not using a method that is adding all the data to the listbox this will not work. And using the bindingsource method mentioned above would be the next best thing.

here is an example of my DataDistro method: My response strings look like this: [Q],ATQuoteLastPrice,value [B],datetime,open,high,low,close,volume

private void DataDistro()
{
    string data = ListBox.Items[0].ToString();
    string[] split = data.Split(new string[] {","}, stringsplitoptions.None);
    if(spit[0] == "[Q]")
    {
        //do some work
    }
    if(split[0] == "[B]")
    {
         //Do some work
    }
}

In your case you would call your method at end of the remove item button click. I would also suggest to make a delegate, or backgroundWorker if the work is extensive. As Calling from a button click Event will be handled by UI Thread.

Everytime the AddData method is called upon, the DataDistro method is also called after data is added.