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 arrayPrivate 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 IfEnd 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, withan 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 IfEnd 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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: