Object Count

  • Thread starter Thread starter Jonathan Wood
  • Start date Start date
J

Jonathan Wood

I was trying to populate a DropDownList control and started by trying the
following code:

Dim i As Integer
Dim li As ListItem = New ListItem

For i = 1 To 50
li.Value = i.ToString()
li.Text = "This is item " + i.ToString()
DropDownList1.Items.Add(li)
Next i

Now, while I'm new to .NET, I've been programming many years and was able to
quickly find another way to make this work.

So I'm not looking for a workaround, but I would like someone to help me
understand why the above code does what it does. What it does is result in
every item in the list with the text "This is item 50". Obviously, the
control saves an object for each item and changes to those items are
reflected in the list. But why is it done this way? Isn't this horribly
inefficent?

Jonathan
 
Dim i As Integer
Dim li As ListItem

For i = 1 To 50
li = New ListItem
li.Value = i.ToString()
li.Text = "This is item " + i.ToString()
DropDownList1.Items.Add(li)
Next i


Try this? I just did it in C#, my syntax may be off for li = New ListItem,
but you do need to reset it like this each time in the loop.
 
because you only create one item object, which you then add 50 times. when
the list is rendered, the item displays its final value. try:

Dim i As Integer
Dim li As ListItem

For i = 1 To 50
li = New ListItem 'create a new item to add
li.Value = i.ToString()
li.Text = "This is item " + i.ToString()
DropDownList1.Items.Add(li)
Next i

-- bruce (sqlwork.com)
 
Hi Jonathan,

It is because you are using the same ListItem object in every Item in the
list. As it is the same item, all the Items will have the same value, and
the last value you assigned was 50. You need to change it to something like
the following:

Dim i As Integer
Dim li As ListItem

For i = 1 To 50
li = New ListItem()
li.Value = i.ToString()
li.Text = "This is item " + i.ToString()
DropDownList1.Items.Add(li)
Next i

While the same variable is being used, it is reassigned to a new object with
each iteration. that object is then added to the Collection.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 
Back
Top