[inline:RemoveHandler.jpg=How to Prevent Events to Fire More Than Once]
If you are new to VB.NET most likely you encounter a problem with events like TextChanged or ValueChanged events.
In VB 6.0, change event is not fired when changing a value programmatically. However, in the .NET version this has been changed.
In order to avoid this problem you need to call a RemoveHandler Statement.
The following code is an example of this.
Public Class Form1
Const curAmount As Double = 100
Private Sub ComputeTotal()
txtTotal.Text = curAmount * txtDays.Text
End Sub
Private Sub dtpFrom_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpFrom.ValueChanged
ComputeTotal()
End Sub
Private Sub dtpTo_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpTo.ValueChanged
ComputeTotal()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim dtpStartDate As Date
'Remove/comment the line below to simulate the error
RemoveHandler dtpTo.ValueChanged, AddressOf dtpTo_ValueChanged
dtpStartDate = dtpFrom.Value
dtpTo.Value = System.DateTime.FromOADate(dtpStartDate.ToOADate + 1)
AddHandler dtpTo.ValueChanged, AddressOf dtpTo_ValueChanged
txtDays
.Text = dtpTo
.Value.Subtract(Format(dtpFrom
.Value,
"Short Date")).Days.ToString
ComputeTotal()
End Sub
End Class
Remove the line: RemoveHandler dtpTo.ValueChanged, AddressOf dtpTo_ValueChanged
to produce the error.