Odin Mostert
Odin Mostert

Reputation: 72

Clicking cancel when entering values in inputbox not exiting procedure

I use an inputbox in my project to get data to input into a database. The problem is that if the user clicks cancel on the input box it takes the default value in the inputbox. How can I exit the procedure if cancel is clicked? This is how my inputbox looks:

sTeamName := inputbox('Team Name','Enter a team name','Phillies');

Here if the user were to click cancel, sTeamName will = 'Phillies'. I can't validate that the default value is stored in the variable, because the default value is possibly what the user wants to enter. Is there like a if inputbox.cancel.click exit or something?

Upvotes: 1

Views: 1120

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596216

if the user clicks cancel on the input box it takes the default value in the inputbox

That is by design, and is documented behavior:

If the user chooses the Cancel button, InputBox returns the default value. If the user chooses the OK button, InputBox returns the value in the edit box.


I can't validate that the default value is stored in the variable, because the default value is possibly what the user wants to enter.

Use a blank string for the default instead, eg:

sTeamName := InputBox('Team Name', 'Enter a team name', '');
if sTeamName <> '' then begin
  // use sTeamName as needed...
end else
begin
  // cancelled, do something else
end;

Otherwise, use InputQuery() instead, as shown in @AndreasRejbrand's answer. The documentation states:

Use the InputBox function when there is a default value that should be used when the user chooses the Cancel button (or presses Esc) to exit the dialog. If the application needs to know whether the user chooses OK or Cancel, use the InputQuery function instead.

Upvotes: 0

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108963

You need to use the InputQuery function instead. This returns a boolean which is False iff the dialog was cancelled, and saves the input string in a var parameter:

var
  S: string;
begin
  S := 'My New Team';
  if InputQuery('Team Name', 'Enter a team name:', S) then
    ShowMessageFmt('You entered "%s".', [S]);

Upvotes: 6

Related Questions