Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB4,VB5,VB6
Expertise: beginner
Aug 21, 1999

Use ActiveControl to stop a loop

Often your user interface includes fields whose contents mutually depends on other fields. A typical example is when you deal with conversions from one measurement unit to another. Let's say that you want to let your users enter a temperature either in Celsius or Fahrenheit degrees, so you provide two textbox controls, and whenever the user enters a value in either textbox, the other is automatically updated.

The instinctive code to handle the conversion would be as below:


' this code assumes that the two textboxes belong to a control array
Private Sub txtTemperature_Change(Index As Integer)
    If Index = 0 Then   'C to F....
        txtTemperature(1) = (9# * val(txtTemperature(0)) / 5) + 32
    Else                'F to C....
        txtTemperature(0) = 5# * (val(txtTemperature(1)) - 32) / 9
    End If
End Sub
Unfortunately, this may cause an endless loop. If the user enters a Celsius temperature, the sub is called with an index of 0, and the Fahrenheit temperature is calculated. That then causes the sub to be called again, with an index of 1, so the Celsius temperature is calculated. If there are rounding or precision errors in the calculations, this loop could become endless.

By using the ActiveControl property, the conversion is performed only if that textbox is the active control. This means that the conversion is not done if the change in temperature was done by code. You can see this concept in action in the following code example:


Private Sub txtTemperature_Change(Index As Integer)
    If Me.ActiveControl Is txtTemperature(Index) Then    
        ' modify only if the chhange was cause by the user
        If Index = 0 Then   'C to F....
            txtTemperature(1) = (9# * val(txtTemperature(0)) / 5) + 32
        Else                'F to C....
            txtTemperature(0) = 5# * (val(txtTemperature(1)) - 32) / 9
        End If
    End If
End Sub
If the user enters a Celsius temperature, the sub is called with an index of 0. The specific textbox is the active control, and the Fahrenheit temperature is calculated. That then causes the sub to be called again with an index of 1. But this time, the specific textbox is NOT the active control, so the calculation is skipped, and the loop is broken.
Heather McCaslin
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date