将函数添加到事件运行时

时间:2017-06-04 18:32:19

标签: delphi

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事件? 我尝试只是分配,但compiller说:[dcc32错误] OrderAdd.pas(66):E2010不兼容的类型:' TNotifyEvent'和'程序,无类型指针或无类型参数'

1 个答案:

答案 0 :(得分:3)

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

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;