Search code examples
delphidelphi-7

Cancel Button in Inputbox doesn't close


I am using an inputbox on a click of a button to store a value and perform some validations on the same. My problem is on click of cancel button it doesn't close and instead popups out information for a null check. Any help is appreciated. Thanks

For a null check it pops out "please enter a value and try again".
The problem is even if i click on cancel it shows the same message like "please enter a value and try again" and when i dont provide any value and click on ok it shows the same message "please enter a value and try again"

procedure TForm1.Button1Click(Sender: TObject);
var inputValue:string;
begin
  repeat
    inputValue:=InputBox('Enter a value', 'value','');
    if (inputValue<>'') then
    begin
      if MessageDlg('Do You want to enter this value ' +inputValue+'?',mtInformation,[mbYes,mbNo],0)= mrYes then
        MessageDlg('Your Value got stored', mtInformation,[mbOk],0)
    end;
  until(inputValue='');

  repeat
    if (inputValue = '') then
      MessageDlg('Please Enter a value and try again', mtInformation,[mbOk],0) ;
    inputValue:=InputBox('Enter a value', 'value','');
    if (inputValue<>'') then
    begin
      if MessageDlg('Do You want to enter this value ' +inputValue+'?',mtInformation,[mbYes,mbNo],0)= mrYes then
        MessageDlg('Your Value got stored', mtInformation,[mbOk],0)
    end;
  until (inputValue<>'') ;
end;

Solution

  • The problem is that your parameter default for function InputBox is empty string. Empty string also is value that function returned when user is pressed "Cancel" button.

    If the user presses OK, the default or user entered data is stored in the return string, otherwise an empty string is returned.

    In this case you can not determine where it came from this value(From Ok or from Cancel).

    I recommend to use InputQuery instead InputBox.

    Something like :

    var
      InputValue : string;
      CustIsPressOK : boolean;
    begin
    
      repeat
        CustIsPressOK := InputQuery('Enter a value', 'value',InputValue);
    
        if CustIsPressOK then
          begin
            if InputValue <> '' then
              begin
                if MessageDlg('Do You want to enter this value ' +inputValue+'?',mtInformation,[mbYes,mbNo],0)= mrYes then
                  MessageDlg('Your Value got stored', mtInformation,[mbOk],0);
              end
            else
              begin
                //user is pressed OK button but value is empty string
                MessageDlg('Please Enter a value and try again', mtInformation,[mbOk],0) ;
              end;
          end;
        until (CustIsPressOK = false) or (CustIsPressOK and (InputValue <> ''));