How to Prevent Events to Fire More Than Once

[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.

  1. Public Class Form1
  2.     Const curAmount As Double = 100
  3.    
  4.     Private Sub ComputeTotal()
  5.         txtTotal.Text = curAmount * txtDays.Text
  6.     End Sub
  7.  
  8.     Private Sub dtpFrom_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpFrom.ValueChanged
  9.         ComputeTotal()
  10.     End Sub
  11.  
  12.     Private Sub dtpTo_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpTo.ValueChanged
  13.         ComputeTotal()
  14.     End Sub
  15.  
  16.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  17.         Dim dtpStartDate As Date
  18.  
  19.         'Remove/comment the line below to simulate the error
  20.         RemoveHandler dtpTo.ValueChanged, AddressOf dtpTo_ValueChanged
  21.  
  22.         dtpStartDate = dtpFrom.Value
  23.  
  24.         dtpTo.Value = System.DateTime.FromOADate(dtpStartDate.ToOADate + 1)
  25.  
  26.         AddHandler dtpTo.ValueChanged, AddressOf dtpTo_ValueChanged
  27.  
  28.         txtDays.Text = dtpTo.Value.Subtract(Format(dtpFrom.Value, "Short Date")).Days.ToString
  29.  
  30.         ComputeTotal()
  31.     End Sub
  32. End Class

Remove the line: RemoveHandler dtpTo.ValueChanged, AddressOf dtpTo_ValueChanged to produce the error.

Comments

Do you have a "grading utility system" which the authorized user can upload a file, an excel file in particular..i have no idea how to do it, it is our project in our visual basic programming... pls help me

Add new comment