• We just launched and are currently in beta. Join us as we build and grow the community.

How to Prevent Events to Fire More Than Once

silvio71

Fun-Time Officer
S Rep
0
0
0
Rep
0
S Vouches
0
0
0
Vouches
0
Posts
161
Likes
154
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
[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. Private

    Sub

    ComputeTotal(

    )
  4. txtTotal.

    Text

    =

    curAmount *

    txtDays.

    Text
  5. End

    Sub

  6. Private

    Sub

    dtpFrom_ValueChanged(

    ByVal

    sender As

    System.

    Object

    , ByVal

    e As

    System.

    EventArgs

    )

    Handles

    dtpFrom.

    ValueChanged
  7. ComputeTotal(

    )
  8. End

    Sub

  9. Private

    Sub

    dtpTo_ValueChanged(

    ByVal

    sender As

    System.

    Object

    , ByVal

    e As

    System.

    EventArgs

    )

    Handles

    dtpTo.

    ValueChanged
  10. ComputeTotal(

    )
  11. End

    Sub

  12. Private

    Sub

    Form1_Load(

    ByVal

    sender As

    System.

    Object

    , ByVal

    e As

    System.

    EventArgs

    )

    Handles

    MyBase

    .

    Load
  13. Dim

    dtpStartDate As

    Date

  14. 'Remove/comment the line below to simulate the error
  15. RemoveHandler

    dtpTo.

    ValueChanged

    , AddressOf

    dtpTo_ValueChanged

  16. dtpStartDate =

    dtpFrom.

    Value

  17. dtpTo.

    Value

    =

    System.

    DateTime

    .

    FromOADate

    (

    dtpStartDate.

    ToOADate

    +

    1

    )

  18. AddHandler

    dtpTo.

    ValueChanged

    , AddressOf

    dtpTo_ValueChanged

  19. txtDays.

    Text

    =

    dtpTo.

    Value

    .

    Subtract

    (

    Format

    (

    dtpFrom.

    Value

    , "Short Date"

    )

    )

    .

    Days

    .

    ToString

  20. ComputeTotal(

    )
  21. End

    Sub
  22. End

    Class

Remove the line: RemoveHandler

dtpTo.

ValueChanged

, AddressOf

dtpTo_ValueChanged

to produce the error.

 

440,010

316,559

316,568

Top