tags:

views:

184

answers:

2

Hello,

I'm encountering an interesting issue with the following code. productObject is a custom object that contains a number of product-related variables including a 'VendorLocationId'.

Given these items in a listbox:

"Town A" value:1

"Town B" value:2

Also given: both items are selected within the listbox.

1  productObjectArray[] productObjectArray = new productObjectArray[lstLocation.Items.Count];
2  int counter = 0;
3  foreach (ListItem li in lstLocation.Items)
4  {
5    if (li.Selected == true)
6    {
7      productObject.VendorLocationId = li.Value;
8      productObjectArray[counter] = productObject;
9    }
10   counter++;
11 }

After executing, the above code gives this result:

productObjectArray[0].VendorLocationId = 2
productObjectArray[1].VendorLocationId = 2

I find this perplexing. If I step through the code, productObjectArray[0].VendorLocationId = 1 and counter = 1 until line 7. Then productObjectArray[0].VendorLocationId magically equals 2 and counter = 1.

+1  A: 

It seems that your "productObject" is declared outside of this code block, and you're therefore referencing both elements in your array to the same object. Therefore, when you change "productObject" the final time in the loop, it affects all of the items in the array, because they are all pointing to the same exact object. What you need to do is have each element in the array point to a new instance of your object.

BFree
Exactly right, thank you. I've fixed the code by generating a new object for each array item.
Paulj
+1  A: 

It looks like you are using a single instance of productObject and setting the two items in productObjectArray to both point to that single instance. VendorLocationId is 2 in both because that was the last value set to productObject.

DocMax