|
|
|
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: |
Click here to copy the following block | Private Sub txtTemperature_Change(Index As Integer) If Index = 0 Then txtTemperature(1) = (9# * val(txtTemperature(0)) / 5) + 32 Else 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: |
Click here to copy the following block | Private Sub txtTemperature_Change(Index As Integer) If Me.ActiveControl Is txtTemperature(Index) Then If Index = 0 Then txtTemperature(1) = (9# * val(txtTemperature(0)) / 5) + 32 Else 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.
|
|
|
|
Submitted By :
Nayan Patel
(Member Since : 5/26/2004 12:23:06 PM)
|
|
|
Job Description :
He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |
View all (893) submissions by this author
(Birth Date : 7/14/1981 ) |
|
|