1
votes

I had create simple project contain 3 of TEdit, 1 of TButton and 3 of string and boolean variable. How i create procedure or function to set Button.Enable := True when each of value in TEdit had change. Need to reduce coding by create procedure or function to do it instead of below code.

type
TForm1 = class(TForm)
  Edit1: TEdit;
  Edit2: TEdit;
  Edit3: TEdit;
  btnSave: TButton;
  procedure FormCreate(Sender: TObject);
  procedure Edit1Exit(Sender: TObject);
private
  { Private declarations }
public
  strWelcome, strTo, strThailand: String;
  modify1, modify2, modify3 : Boolean;
  { Public declarations }
end;

Oncreate of Form i consign 3 strings value to 3 TEdit.Text and set modify variable to False

procedure TForm1.FormCreate(Sender: TObject);
 begin
   strWelcome := 'Welcome';
   strTo      := 'To';
   strThailand:= 'Thailand';

   modify1 := false;
   modify2 := false;
   modify3 := false;

   Edit1.text := strWelcome;
   Edit2.text := strTo;
   Edit3.text := strThailand;
end;

Onexit of 3 TEdit assign to Edit1Exit(Sender: TObject); for checking text value still equals the initial value or not? If some of TEdit.Text had change btnSave will be enable.

procedure TForm1.Edit1Exit(Sender: TObject);
begin
  if Edit1.Text = strWelcome then
    modify1 := False
  else
    modify1 := True;
  if Edit2.Text = strTo then
    modify2 := False
  else
    modify2 := True;
  if Edit3.Text = strThailand then
    modify3 := False
  else
    modify3 := True;
  btnSave.Enabled := modify1 or modify2 or modify3;
end;

Any idea to create procedure or function to reduce above code. :)

1

1 Answers

2
votes

You could use arrays to make this more concise but with just three items it's probably not worth it. If this is really all the code under consideration I'd write it like this:

procedure TForm1.Edit1Exit(Sender: TObject);
begin    
  btnSave.Enabled :=
    (Edit1.Text <> strWelcome) or
    (Edit2.Text <> strTo) or
    (Edit3.Text <> strThailand);
end;

You should remove the three boolean fields. They are no longer used and in any case should have been locals or exposed as properties with getter functions. And you should convert the strXXX variables into constants since I assume they do not change.

I'd also suggest giving your edit controls informative names.