? bug in listbox.AddRange : duplication

  • Thread starter Thread starter Guest
  • Start date Start date
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);

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

}
 
Back
Top