1

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.