Search code examples
delphidelphi-7

Need to enable button when text is entered in the edit boxes


I would like to use 2 TEdit item and a button for this. How can I check if all the Edit have some text value. After that i want to activate a button.

Main form Onshow event: Btn1.Enabled:=false;

if Edit1.text + Edit2.text have value then btn1.enabled:=true ?

Thanks for the help!


Solution

  • Are you using actions? If not, you should consider it.

    Add a TActionList to your application if you don't already have one. Next, add a TAction to it. Set the action's properties so it resembles the button. (I.e., set the caption, and move the button's OnClick event handler to the action's OnExecute handler.) Assign the button's Action property to refer to the new action object.

    Finally, handle the action's OnUpdate event. In it, enable or disable the action as needed. The button (and any other controls you later choose to associate with the same action) will be updated accordingly.

    procedure TSteveForm.ButtonActionUpdate(Sender: TObject);
    begin
      TAction(Sender).Enabled := (Edit1.Text <> '') and (Edit2.Text <> '');
    end;
    

    This looks very similar to handling the OnChange events of the edit controls, but its differences become apparent when the scenario changes:

    1. If you add or remove edit controls, you only have to change this one procedure to ensure the button is enabled correctly. If you're handling OnChange events, you need to change the procedure and assign it to each new control's OnChange property.
    2. Not all controls have a convenient OnChange event that lets you know when something has changed. Actions' OnUpdate events relieve you from having to know exactly when an update is appropriate. They run while the program is idle and on demand.