• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 460
  • Last Modified:

Listbox.Clear not clearing

I have a form with a button and a listbox.

When the button is clicked, it calls Listbox.Clear, and then fires off a new thread.
That thread, via an event (processing code which is on the form class) inserts items in the list.

I then click the button again, stick a breakpoint on List.Clear(), after its called the Count property gets set to 0, however the "entries" field (found inside "items") is still populated with all the objects I added.  As a result the second time round I duplicate the entries in the listbox.

I've tried calling Listbox.Refresh/Update all over the place, also using Listbox.Invoke to add the item on the same thread (dispite requires invoke returning false).  I'm very confused.

Additional info:
I don't kill/abort the thread at any point, just let it run to the end of the method in its threadstart.  When the button is clicked again, a new instance of the thread is created, which then runs.

Thanks in advance.
  • 3
1 Solution
Ramesh SrinivasTechnical ConsultantCommented:
How are you binding data to the listbox?

If you are using a datasource you need to set the listbox's datasource property to Nothing or null and rebind.

FSIFMAuthor Commented:
Data is simply being added through Listbox.Items.Add(obejct) - there is no binding in use.
FSIFMAuthor Commented:
If you make the change without using events, the problem does not occurs.  The code attached isolates the issue.

Create a new C# windows app project, create a new listbox, and paste my code in.

If you swap the commented lines in method AddItem, it works as expected.

Any thoughts?
public delegate void del(object sender, EventArgs e);
public event del evt;
private void listBox1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
	this.evt += new del(addEvent);
	System.Threading.Thread _thread = new System.Threading.Thread(new System.Threading.ThreadStart(AddItem));
private void AddItem()
	//listBox1.Items.Add("Data Item");
	evt(this,new EventArgs());
private void addEvent(object sender, EventArgs e)
	listBox1.Items.Add("Data Item");

Open in new window

FSIFMAuthor Commented:
My colleague pointed it out to me.  It's because each time I click the list box, i'm adding a new event handler to the existing handler(s) each time, so it runs more than once.

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now