Setting the OnClick procedure of a Delphi button at runtime

后端 未结 2 1280
青春惊慌失措
青春惊慌失措 2021-01-17 05:38

I have a program in which I need to update a database table with information entered into edit boxes, with a button at the end to do the updating. However, the form is creat

2条回答
  •  北海茫月
    2021-01-17 06:04

    Have you thought about descending a control from TButton with the edit controls as field members?

    Here's an example that hopefully you can glean some ideas from.

      TButtonHack = class(TButton)
        fEdit1,
        fEdit2,
        fEdit3: TEdit;
      procedure Click; override;
      public
      constructor Create(AOwner: TComponent; AParent: TWinControl; Edit1, Edit2, Edit3: TEdit); Reintroduce;
    end;
    
    Constructor TButtonHack.Create(AOwner: TComponent; AParent: TWinControl;  Edit1, Edit2, Edit3: TEdit);
    begin
      inherited Create(AOwner);
      Parent := AParent;
      Left := 100;
      Top := 100;
      Width := 100;
      Height := 20;
      Caption := 'ButtonHack';
      fEdit1 := Edit1;
      fEdit2 := Edit2;
      fEdit3 := Edit3;
    end;
    
    procedure TButtonHack.Click;
    begin
      Inherited Click;
      Showmessage(fEdit1.text+','+ fEdit2.text+','+fEdit3.text);
    end;
    

    To test, drop a button, and three TEdits on a form.

    procedure TForm1.Button1Click(Sender: TObject);
    var
      ButtonHack: TButtonHack;
    begin
      ButtonHack := TButtonHack.Create(Form1, Form1, Edit1, Edit2, Edit3);
    end;
    

    Whether you create the edits ahead of time or from within the TButtonHack is up to you. I've simplified it as much as possible just as an example.

提交回复
热议问题