PJW
PJW

Reputation: 5417

Can't clear a Winforms-ListBox

This is a rather simply question - but it's defeated me so far.

I have two list boxes on my form. When the user clicks an item in the first box, the second list box populates with related values. However sometimes I later want to clear the second listbox so it appears empty again.

However, none of the following seems to work:

lbxQuantity.Items.Clear();
lbxQuantity.DataSource = null;
lbxQuantity.Text = "";

How do I completely clear the listbox of all values and just leave it blank?

The listbox is in a WinForms application ad I'd like to add a button that clears all listboxes on the form.

Upvotes: 3

Views: 5773

Answers (1)

Andreas
Andreas

Reputation: 6465

It depends on which method you're using to fill the ListBox.

  • If you're manually adding the items by calling listBox.Items.Add you can clear it through listBox.Items.Clear.
  • If you're populating it through the DataSource, DisplayMember, and ValueMember properties you can set DataSource = null and then call listBox.Items.Clear in the DataSourceChanged event handler when the DataSource is null. You can of course also do it right after the null assignment.

Another possibility for the behavior you're seeing could be that listbox is repopulated in your own code through some event as soon as you remove all items.

Upvotes: 7

Related Questions