? bug in listbox.AddRange : duplication

G

Guest

Who can explain this ?? : I expect 2 but I get 4 items !

private void button1_Click(object sender, EventArgs e)
{
object[] bunchOfStuff = { "foo", "fee" };
listBox1.Items.Clear();
System.Windows.Forms.ListBox.ObjectCollection lboxObjCol = new
ListBox.ObjectCollection(listBox1, bunchOfStuff);
listBox1.Items.AddRange(lboxObjCol);

}
 
N

Nicholas Paldino [.NET/C# MVP]

Andrew,

Well, you are adding the objects twice. The first time is in the
constructor, where you pass bunchOfStuff, the second is when you call
AddRange, passing the array again, resulting in four items.

Hope this helps.
 
G

Guest

Andrew,
This isn't a bug. This line:

System.Windows.Forms.ListBox.ObjectCollection lboxObjCol = new
ListBox.ObjectCollection(listBox1, bunchOfStuff);

actually adds your 2 items to the Listbox. So the next line simply does it
again.

Comment out the last line and you will have what you want.
Peter
 
G

Guest

Thanks - I can see now why it is loaded 2X thanks to you and Nicholas for
setting me straight :)
--
Andrew


Peter Bromberg said:
Andrew,
This isn't a bug. This line:

System.Windows.Forms.ListBox.ObjectCollection lboxObjCol = new
ListBox.ObjectCollection(listBox1, bunchOfStuff);

actually adds your 2 items to the Listbox. So the next line simply does it
again.

Comment out the last line and you will have what you want.
Peter

--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com




andrewcw said:
Who can explain this ?? : I expect 2 but I get 4 items !

private void button1_Click(object sender, EventArgs e)
{
object[] bunchOfStuff = { "foo", "fee" };
listBox1.Items.Clear();
System.Windows.Forms.ListBox.ObjectCollection lboxObjCol = new
ListBox.ObjectCollection(listBox1, bunchOfStuff);
listBox1.Items.AddRange(lboxObjCol);

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top