Problem modifying item properties in a list, using For Each

markfaz

New member
Joined
Aug 27, 2012
Messages
3
Programming Experience
1-3
Hello all!
First post for me on these pages, so please be gentle.:)

My problem is as follows. I have a List(of Point) that stores the current mouse location coordinates when the user clicks inside a picture box. The picture box paint event then draws a small FillRectangle using those coordinates and does the same for each following click, as well as drawing a line between each point.

I used the following code in the picture box paint event to paint the rectangles and draw the lines:

VB.NET:
For Each p As Point In pointsList
            e.Graphics.FillRectangle(Brushes.Blue, p.X - 2, p.Y - 2, 5, 5)
        Next

Dim i As Integer = 0

If pointsList.Count > 1 Then
            For i = 1 To pointsList.Count - 1
                e.Graphics.DrawLine(Pens.HotPink, pointsList.Item(i - 1), pointsList.Item(i))
            Next
        End If

All of the above works fine with no errors.

I've made four buttons (labeled Up, Down, Left, Right) and when clicked I'd like the rectangles and lines to move by 50 pixels in the chosen direction. I've tried to do this with the following code in, for example, the Up Button's click event:

VB.NET:
For Each p As Point In pointsList
            p.Y += 50
        Next

PictureBox1.Invalidate()

This causes no errors, but no movement either. I put a Watch on pointsList and the coordinates aren't updating as I expected.
I've searched Google, and found a number of pages suggesting that using this method doesn't actually affect pointsList itself, rather a copy of pointsList.
I've been unable to find any explanation as to how I can modify an item's property when contained in a list using a For Each loop.

Anyone able to help?

Cheers,
Mark.
 
I've been unable to find any explanation as to how I can modify an item's property when contained in a list using a For Each loop.
You can't, Point is a Structure, which is a value type. By using a For-Next indexed loop you can retrieve the Point value, modify it, then assign that back in list.
 
I've searched Google, and found a number of pages suggesting that using this method doesn't actually affect pointsList itself, rather a copy of pointsList.
It's not a copy of the list, but rather a copy of the item in the list. If you're list contained reference types then getting an item would involve getting a reference to the object in the list. Because your list contains value types, getting an item involves getting a copy of the value in the list. Modifying that copy has no effect on the original value. For the sake of others who may view this thread, presumably you are now doing something like this:
Dim p As Point

For i As Integer = 0 To pointsList.Count - 1
    p = pointsList(i)
    p.Y += 50
    pointsList(i) = p
Next
That gets a copy of the value from the list, modifies that copy and then copies the copy back over the original.
 
Back
Top