Effective form design involves not only capturing user data but also ensuring that the data is in the correct format before processing.
1. Retrieving Input Data
The most common input component is TEdit. To retrieve the data entered by the user, you access its Text property.
- String Focus: Remember that the
Textproperty always returns a String type, even if the user entered numbers. - Conversion: To use the input data in mathematical calculations or comparisons, you must explicitly convert the string to the required numerical type using built-in conversion functions.
| Function | Purpose | Example |
StrToInt(S) | Converts a string to an Integer. | I := StrToInt(Edit1.Text); |
StrToFloat(S) | Converts a string to a Double (Floating Point). | R := StrToFloat(Edit2.Text); |
TryStrToInt(S, V) | Safely attempts string-to-integer conversion. Returns True or False. | Success := TryStrToInt(S, I); |
Example: Calculating a Sum
procedure TForm1.btnCalculateClick(Sender: TObject);
var
A, B, Sum: Integer;
begin
try // Start exception handling block
// Conversion is necessary to treat the text as numbers
A := StrToInt(edtValueA.Text);
B := StrToInt(edtValueB.Text);
Sum := A + B;
// Convert back to string to display
lblResult.Caption := IntToStr(Sum);
except
// If StrToInt fails (e.g., user enters "abc"), an exception is caught
ShowMessage('Error: Please enter valid whole numbers.');
end;
end;
2. Basic Validation
Validation ensures the data is usable. In the example above, the try...except block handles runtime conversion errors. For a better user experience, you should perform validation before attempting conversion.
A. Checking for Empty Input
Always ensure required fields are not left blank.
if Trim(edtName.Text) = '' then
begin
ShowMessage('The Name field is required.');
edtName.SetFocus; // Sets the cursor back to the input field
Exit; // Stop the procedure execution
end;
Trim()Function: Used to remove any leading or trailing whitespace from the input string before checking if it’s empty.
B. Safe Conversion with TryStrToInt
The TryStrToInt function is a crucial tool for robust validation, as it prevents the program from crashing if the user enters non-numeric data.
var
Age: Integer;
begin
if not TryStrToInt(edtAge.Text, Age) then
begin
ShowMessage('Age must be a valid number.');
Exit;
end;
if (Age < 0) or (Age > 150) then
begin
ShowMessage('Age value is outside the valid range.');
Exit;
end;
// Data is now guaranteed to be a valid Integer between 0 and 150
// ... proceed with calculation
end;
3. Using Message Dialogs (ShowMessage and MessageDlg)
Delphi provides simple, blocking modal dialogs for displaying messages to the user.
ShowMessage(S): Displays a simple message with an OK button. (Used in most examples above).MessageDlg(Msg, DlgType, Buttons, HelpCtx): Displays a complex dialog with custom icon and button combinations, returning a result based on the user’s button press.
Example: Confirmation Dialog
The MessageDlg is ideal for asking the user for confirmation.
var
Result: Integer;
begin
Result := MessageDlg('Are you sure you want to delete this record?',
mtConfirmation,
[mbYes, mbNo], // Display Yes and No buttons
0);
if Result = mrYes then // mrYes is the constant for the Yes button response
begin
// User confirmed deletion
DeleteRecord;
end
else
begin
// User cancelled the operation
ShowMessage('Operation cancelled.');
end;
end;
4. Input Masks (TMaskEdit)
For strictly structured input (like phone numbers, dates, or product codes), the TMaskEdit component provides automatic formatting and validation.
- How it Works: You define an
EditMaskproperty in the Object Inspector (e.g.,!(999) 000-0000;1;for a phone number). The mask ensures the user can only enter characters in allowed positions, greatly simplifying validation logic in your code.
