chacham
New member
- Joined
- Nov 28, 2023
- Messages
- 4
- Programming Experience
- 10+
Can someone explain the difference to me?
The 1st row of buttons, when clicked, set the 3rd button to "3".
The 2nd row of buttons, when clicked, set their own button to 1, 2, or 3.
It seems that adding a handler that uses a variable, uses the variable's value at event time, not at the handler's creation time. Dimming the variable inside the loop creates a new variable each time, and so the variable used in the Handler never changes. I'm curios if there is a way to change this behavior, so that the variable's value at handler creation time is used.
VB.NET:
Public Class Form1
Private Sub Form1_Load(Sender As Object, Arguments As EventArgs) Handles MyBase.Load
Dim A As Integer
Dim B As Button
For X As Integer = 1 To 3
A = X
B = New Button With {.Location = New Point(100 * X, 0)}
AddHandler B.Click, Sub() B.Text = A
Controls.Add(B)
Next
For X As Integer = 1 To 3
Dim C As Integer = X
Dim D As New Button With {.Location = New Point(100 * X, 25)}
AddHandler D.Click, Sub() D.Text = C
Controls.Add(D)
Next
For Each Control As Control In Controls
DirectCast(Control, Button).PerformClick()
Next
End Sub
End Class
The 1st row of buttons, when clicked, set the 3rd button to "3".
The 2nd row of buttons, when clicked, set their own button to 1, 2, or 3.
It seems that adding a handler that uses a variable, uses the variable's value at event time, not at the handler's creation time. Dimming the variable inside the loop creates a new variable each time, and so the variable used in the Handler never changes. I'm curios if there is a way to change this behavior, so that the variable's value at handler creation time is used.