# GAMBAS BOOK 3.18.4

## Control elements 1

### Chapters

08.10.2022
k16:k16.6:k16.6.3:start

## 16.6.3 Examples for using a TextBox - Validation of input

Securing the use of valid data in a program is part of the concept for avoiding runtime errors. In → chapter 16.6.2 Valid Data you will find information on the topic and approaches how to validate data from TextBoxes and their different specializations (MaskBox, ValueBox, HistoryBox, InputBox and ButtonBox). For the input of complex numbers, matrices, polynomials or vectors you will find examples in the chapters 29.1 Complex Numbers, 29.3.3 Matrix, 29.3.4 Polynomial and 29.3.5 Vector.

There is no generally valid procedure for checking whether an input string from a TextBox can be converted to a valid date - if the specializations cannot be used. However, the following examples should show you how to use different strategies to provide a program with valid data from an input string for processing.

## 16.6.3.1 Example 1

A number A is recorded in a TextBox and an average measured value (without unit) as a real number R in another TextBox. From the two inputs, a quotient with four decimal places is calculated in the program QM = (A²-Pi) / R and output in a third TextBox (read only). The contents of the output TextBox are deleted each time the entries are changed.

Figure 16.6.3.1.1: Calculation of QM

Before you get started quickly, you should consider the following hints in peace and quiet, although the order does not correspond to any order of precedence:

• The entries in the TextBoxes are of the data type String. To calculate the quotient, however, you need figures.
• When entering into the two TextBoxes, you should limit the input alphabet appropriately.
• While only single digits are allowed for entering the number as characters, the input alphabet for the real number can be written down in this way: {+-,0123456789}.
• Defining the second alphabet, for example, does not in any way protect you from completely pointless entries such as' +0,874-, 9', which forces you to validate the data. You must check whether the input string from the TextBox for the mean value R can be safely converted into a real number.
• The conversion of the comma used in our language area into a dot must be realized internally within the program.
• The numbers - stored in a suitably named variable - must be converted to the Integer data type, where it has been specified not to allow the number 0 as a valid date, which is to be checked. However, this has no effect on the input alphabet {0123456789} because otherwise, for example, the number 10 would be impossible.
• The measured value R is in good hands in a variable of the data type float. The conversion to this type must take this into account.
• Gambas provides you with CFloat (Value As Variant) a suitable function for the conversion.
• In order not to provoke an error' division by zero' when calculating the quotient, the input of a zero has to be filtered out and after an indication to the user a correction for the faulty denominator has to be offered.
• Before you start the calculation, you should check whether the input text boxes are not empty. In this case, interrupt the program flow, inform the user in an appropriate manner and offer correction possibilities.

The source code is presented in extracts:

``` ' Die Eigenschaft txbResult.ReadOnly wird auf TRUE gesetzt
 Public Sub btnCalculate_Click()
   Dim sInputN, sInputR, sPatternN, sPatternR As String
   Dim iCount As Integer
   Dim fValue, fCoefficient As Float

   If Not txbInteger.Text Then ' Prüfung: TextBox leer?
      Message.Error("Eingabefehler 1!") ' Kommentar in einer MessageBox
      txbInteger.SetFocus ' Fokus auf die TextBox txbInteger setzen
      Return ' Prozedur verlassen
   Endif
   If Not txbReal.Text Then ' Prüfung: TextBox leer?
      Message.Error("Eingabefehler 2!")
      txbInteger.SetFocus
      Return
   Endif

  '----------------------------------------------------------------------------

   sInputN = Trim(txbInteger.Text) ' Leerzeichen am Anfang und am Ende entfernen
   Try iCount = CInteger(sInputN) ' Versuch: Konvertierung String → Ganze Zahl
   If Error Then ' Fehlerbehandlung
      Message("Fehler 1")
      txbInteger.SetFocus
      Return
   Endif

 ' Anzahl Null herausfiltern
   If iCount = 0 Then
      Message.Info("Die Anzahl muss größer als Null sein!")
      txbReal.SetFocus
      Return
   Endif

 '----------------------------------------------------------------------------

   sInputR = Trim(txbReal.Text) ' Leerzeichen am Anfang und am Ende entfernen
 ' Dezimalseparator der aktuellen Locale durch den Punkt ersetzen
   sInputR = Replace\$(sInputR, Left\$(Format\$(0, ".0")), ".")

   Try fValue = CFloat(sInputR) ' Versuch: Konvertierung String → Reelle Zahl
   If Error Then
      Message("Fehler 2")
      txbReal.SetFocus
      Return
   Endif

   If fValue = 0 Then ' Null herausfiltern
      Message.Info("Die (reelle) Zahl 0 ist nicht zulässig!")
      txbReal.SetFocus
      Return
   Endif

 '----------------------------------------------------------------------------

   fCoefficient = Round((iCount * iCount - Pi()) / fValue, -4) ' Berechnung Quotient
   txbResult.Text = Str(fCoefficient) ' Anzeige Quotient (Koeffizient QM)

 End ' btnCalculate_Click()

 '----------------------------------------------------------------------------

 Public Sub txbInteger_KeyPress() ' Umsetzung Eingabe-Alphabet
   CheckInput("0123456789")
 End ' txbDigits_KeyPress()

 Public Sub txbReal_KeyPress() ' Umsetzung Eingabe-Alphabet
   CheckInput("+-,0123456789")
 End ' txbDigits_KeyPress()

 Public Sub CheckInput(sAllowed As String) ' Idee Charles Guerin
   Select Case Key.Code
     Case Key.Left, Key.Right, Key.BackSpace, Key.Delete, Key.End, Key.Home, Key.Enter, Key.Return
       Return
     Default
       If Key.Text And If InStr(sAllowed, Key.Text) Then
          Return
       Endif
   End Select
   Stop Event
 End ' CheckInput(sAllowed As String)

 ' Public Sub txbInteger_Change()
 '    txbResult.Clear
 ' End
 ' Public Sub txbReal_Change()
 '   txbResult.Clear
 ' End

 Public Sub TBIR_Change()
   txbResult.Clear
 End ' TBIR_Change()```

Comment:

• In lines 83 to 88, the requirement is realized that each time the text property in the two text boxes txbInteger and txbReal is changed, the text in the output TextBox is deleted. For two TextBoxes the effort is still justifiable - but with 5 or more? Then it is worthwhile to set the virtual property Group in the IDE of all involved TextBoxes to the same value in each case - here TBIR - and to define a common event handler for all of them. The implementation for the two TextBoxes txbInteger and txbReal can be seen in lines 83 to 85.
• You can still formulate the notes and error messages specifically.
• A simplification would result in lines 20 to 33 by the use of a regular expression, since zero is not accepted as a pattern by the sample check and only correct numbers can be entered:
```   sInputN = Trim(txbInteger.Text)
   sPatternN = "^[1-9][0-9]*\$" ' Alternative mit Null: "^{1}\$|^[1-9][0-9]*\$"
   If sInputN Not Match sPatternN Then
      Message.Error("Eingabefehler 3!")
      txbInteger.SetFocus
      Return
   Endif
   iCount = CInteger(sInputN)```

## 16.6.3.2 Example 2

To ensure that only certain characters - here it is the numbers 0 to 9 - are accepted in a TextBox, the following sample source code is offered in the documentation:

```' My text box only accepts digits

Public Sub MyTextBox_KeyPress()
If Instr("0123456789", Key.Text) = 0 Then
Stop event
Endif
End```

Hints:

• In the gambas documentation it is described that with the stop event you inform the interpreter that the current event should be' canceled'.
• Some events support the action of being aborted. The KeyPress event is one of them. If it is canceled, the keystroke is no longer processed - the input is rejected. It does not matter where Stop Event is located within the event handler. However, it is mandatory to cancel the event.

Works - but unfortunately, you can't correct the sequence of digits in any way, which can be considered a deficiency. Therefore, the following section introduces an improved solution in which you can move the cursor in the TextBox and delete individual digits with the BackSpace key:

```Public Sub txbDigits_KeyPress()
' Nur die Ziffern 0..9 als zulässige Ziffern zulassen
If (Key.Text Not Like "[0-9]") And (Key.Code <> Key.BackSpace) And (Key.Code <> Key.Left) \\
And (Key.Code <> Key.Right) Then
Stop Event
Endif ' Key.Text Not Like "[0-9]" ?
End ' txbDigits_KeyPress() ```

You will undoubtedly still discover a disadvantage - the input alphabet is not variable if you think, for example, of the case that all digits 0-9 are allowed, plus the two sign (+-) and the characters dot, comma and asterisk, as well as the letter x. The input alphabet is not variable. The following solution safely eliminates the disadvantage:

```Public Sub CheckInput(sAllowed As String) ' Idee Charles Guerin
Select Case Key.Code
Case Key.Left, Key.Right, Key.BackSpace, Key.Delete, Key.End, Key.Home, Key.Enter, Key.Return
Return
Default
If Key.Text And If InStr(sAllowed, Key.Text) Then
Return
Endif
End Select
Stop Event

End ' CheckInput(sAllowed As String)

Public Sub txbDigits_KeyPress()
CheckInput("+-,.*0123456789x")
End ' txbDigits_KeyPress()```

The check whether a character entered belongs to the input alphabet or not works without errors. However, remember to check the validity of the input string afterwards if, for example, the input string is to be interpreted as a term in a linear equation. The string -5,88*x+7,1+*23 contains only characters from the input alphabet and is nevertheless not suitable for processing, since it contains a syntax error in the sense of the term specification.

## 16.6.3.3 Example 3

This example does not focus on checking but on prevention, because the user is shown a hint text in the TextBox to minimize incorrect entries. A special TextBox developed by Tobias Boege is used - the Explain-TextBox. The Explain-TextBox is a TextBox, which allows to display an explanatory text (explanation) in the font color grey, if the TextBox is empty and does not have the focus. In this way, you might be able to dispense with explanatory labels in front of the text boxes:

Figures 16.6.3.3.3.1: Explain-TextBox

The class ExplainTextbox is provided in a project in the download area.

## 16.6.3.4 Example 4

It should be checked whether the input of a year number in the interval from 1600 to 2100 in a text box is or will be a leap year.

An astronomical year is the duration of the revolution of the Earth around the central body Sun - our star. In our time units this is 365 days, 5 hours, 48 minutes and 47 seconds. A normal calendar year - but what is already normal - has a length of 365 days. After 4 years, the 5 hours, 48 minutes and 47 seconds, which corresponds to about a quarter of a day, are combined into one day, the 29th of February, and thus a leap year has 366 days. There is a leap year every 4 years, but not every 100 years, but then every 400 years to compensate for the discrepancies of the inserted quarter days to 6 hours. I am thrilled!

As a preventive measure, the number of characters is limited to a maximum of 4 characters:

``` Public Sub Form_Open()
   txbLeapYear.MaxLength = 4
   ...
 End ' Form_Open()```

The function IsLeapYear (..) converts the above rule for leap years and returns the function value True if the year used as argument was or is a leap year:

``` Public Function IsLeapYear(iYear As Integer) As Boolean

   If (iYear Mod 4) = 0 And (iYear Mod 100) <> 0 Or ((iYear Mod 400) = 0) Then
      Return True
   Else
      Return False
   Endif

 End ' Function IsLeapYear(..)```

In the following source code section - which is followed by a comment - you will see various (preliminary) checks:

``` Public Sub txbLeapYear_Activate()
   Dim iCount As Integer
   Dim sInput As String

   sInput = Trim(txbLeapYear.Text) ' Entfernung von Leerzeichen am Anfang und am Ende des Strings

   For iCount = 1 To Len(sInput)
       If Mid(sInput, iCount, 1) Not Like "" Then ' Zeichen-Prüfung auch mit [0-9]
          Message.Error("Eingabefehler - Zeichen!")
          Return
       Endif
    Next

   If Len(sInput) <> 4 Then
      Message.Error("Jahreszahl nicht vierstellig!") ' optional
      Return
   Endif

   If CInt(sInput) < 1600 Or CInt(sInput) > 2100 Then ' Bereichsprüfung [1600..2100]
      Message.Error("Eingabefehler - Bereich!")
      Return
   Endif

   If IsLeapYear(CInt(sInput)) Then ' Prüfung Schaltjahr und Kommentare
      If CInt(sInput) < Year(Now) Then
         Message.Info("Das Jahr " & sInput & " war ein Schaltjahr.")
      Else
         Message.Info("Das Jahr " & sInput & " wird ein Schaltjahr sein.")
      Endif
   Else
      If CInt(sInput) < Year(Now) Then
         Message.Info("Das Jahr " & sInput & " war kein Schaltjahr.")
      Else
         Message.Info("Das Jahr " & sInput & " wird kein Schaltjahr sein.")
      Endif
   Endif

 End ' txbLeapYear_Activate()```

Comment:

• In line 5, variable sInput is assigned the character string that is in the TextBox when the text input has been completed with the Return key.
• In lines 7 to 12, a character scanner checks whether all characters in the input string are digits (0… 9) after blank characters have been removed.
• If not exactly 4 digits have been entered - lines 14 to 17 - a corresponding message is displayed and you can make corrections (option).
• A range check for the specified time period is performed in lines 19 to 22.
• Since the argument of the function IsLeapYear (iYear AS Integer) (line 24) of the data type must be an integer, the input string is converted to an integer with CInt (..), which is also possible without any problems after the successful pre-checks.
• Dependent on the function value, detailed messages about the outcome of the check are displayed.

The alternative presented here uses a regular expression with which all checks are performed in one step:

```Public Sub txbLeapYear_Activate()
Dim sSubject, sPattern As String

sSubject = Trim(txbLeapYear.Text)
sPattern = "^([0-9]{2})|([0-9]{2})|2100\$" ' Check pattern as regular expression

If sSubject Not Match sPattern Then
Message.Error("Eingabefehler!")
Return
Endif

Message.Info(Subst\$("Das Jahr &1 ist &2ein Schaltjahr!",sSubject,IIf(IsLeapYear(CInt(sSubject)),"","k")))

End ' txbLeapYear_Activate()```

## 16.6.3.5 Example 5

With the following source code you can completely synchronize the two TextBoxes txbA and txbB during input:

```Public Sub txbA_Change()
txbB.Text = txbA.Text
End ' txbA_Change()```

## 16.6.3.6 Example 6

```Public Sub txbInput_Activate()
Dim sInput As String = txbInput.Text

' Replace the decimal separator of the current (German) locale with the dot
Print sInput
sInput = Replace\$(sInput, Left\$(Format\$(0, ".0")), ".")
Print sInput

End```

## 16.6.3.7 Example 7

There are n TextBoxes on a form, where the content of k selected TextBoxes (k ≤ n) is to be deleted with one call. The solution is to define a unique selling point for the TextBoxes whose content is to be deleted, and the tag property is a good way to do this.

```Public Sub Form_Open()
FMain.Center

txbBox1.Tag = "L"
txbBox2.Tag = "L"
txbBox4.Tag = "L"
txbBox6.Tag = "L"
...
End ' Form_Open()

Private Sub TBMultiClear()
Dim C As Control
Dim tBox As TextBox
For Each C In Me.Controls
If C Is TextBox Then
If C.Tag = "L" Then
' Print C.Name ' Kontrolle
tBox = C
tBox.Clear
Endif
Endif
Next
End ' TBMultiClear()

Public Sub btnTBClear_Click()
TBMultiClear()
End ' btnTBClear_Click()```

## 16.6.3.8 Example 8

The following task must be processed: When activating the Activate-Event of a textbox A (printing on the return key) a certain action is to be triggered and then the cursor is to be placed in the textbox B, which receives the focus. This is done manually with the tab key if the TextBox B in the hierarchy immediately follows the TextBox A. You define the hierarchy of components in the IDE in the hierarchy window. The following source code also implements the above mentioned behavior:

```Public Sub txb_A_KeyPress()
If Key.Code = Key.Enter Or Key.Code = Key.Return Then
' ACTION ...
txb_B.SetFocus()
' Desktop.SendKeys("\t") ' Alternative if the Desktop component is used
Endif
End ' txb_A_KeyPress()```

The use of the alternative has the advantage that the text is marked in the TextBox B, just like when using the tabulator key. 