关于delphi:向事件运行时添加函数

Add function to event runtime

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
procedure TFormOrderAdd.DBEdit1DblClick(Sender: TObject);
var
  FormSelectEmp: TForm;
  SelectEmpDBGrid: TDBGrid;

begin
  FormSelectEmp := TForm.Create(Self);
  SelectEmpDBGrid :=  TDBGrid.Create(Self);
  SelectEmpDBGrid.Parent := FormSelectEmp;
  SelectEmpDBGrid.Align := alClient;
  SelectEmpDBGrid.DataSource := DMl.DataSourceViewEmpList;
  FormSelectEmp.ShowModal;
  SelectEmpDBGrid.OnDblClick := AddSelectedEmp;
  FormSelectEmp.Close;
end;

procedure TFormOrderAdd.AddSelectedEmp;
begin
  DBEdit1.Text := Dml.ADOQueryViewEmpList.FieldByName('ID').Text;
end;

如何将我的程序添加到 OnDblClick 事件?
我尝试分配,但编译器说:[dcc32 Error] OrderAdd.pas(66): E2010 Incompatible types: 'TNotifyEvent' and 'procedure, untyped pointer or untyped parameter'


您必须在一个类中创建一个匹配的事件方法原型,然后将其分配给事件处理程序(对于 TDBGrid 控件的 OnDblClick 事件,它是 TNotifyEvent),因此您可以编写例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
type
  TForm1 = class(TForm)
    DBEdit1: TDBEdit;
    DBGrid1: TDBGrid;
  private
    procedure Form1Create(Sender: TObject);
    procedure MyGridDblClick(Sender: TObject);
  end;

implementation

procedure TForm1.Form1Create(Sender: TObject);
begin
  { it doesn't matter if you create the component at runtime,
    this is a common principle of assigning event methods at
    runtime - they just have to match the method prototypes }

  DBGrid1.OnDblClick := MyGridDblClick;
end;

procedure TForm1.MyGridDblClick(Sender: TObject);
begin
  { to access the grid instance in case more than one grid
    uses this handler you can use TDBGrid(Sender) or safer
    cast (Sender as TDBGrid) }

  DBEdit1.Text := TDBGrid(Sender).DataSource.Dataset.FieldByName('ID').Text;
end;