在运行时设置Delphi按钮的OnClick过程 [英] Setting the OnClick procedure of a Delphi button at runtime

查看:149
本文介绍了在运行时设置Delphi按钮的OnClick过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,其中我需要使用输入到编辑框中的信息来更新数据库表,最后还有一个按钮来进行更新.但是,该表单是在运行时创建的,并且包括按钮在内的所有元素也都以相同的方式创建.我想出了一种允许数据库参数的方法是定义一个更新数据库的过程,例如:

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 created at runtime and all the elements including the button are also created in the same way. I figured a way to allow the database arguments would be to define a procedure to update the database such as:

procedure UpdateDatabase(Field1,Field2,Field3:string);
begin
//update database here...
end;

然后使用预先填充的参数将我按钮的OnClick事件分配给此过程,例如:

Then assign the OnClick event of my button to this procedure with the parameters pre filled like:

Button1.OnClick := UpdateDatabase(Edit1.text,Edit2.Text,Edit3.Text);

但是类型不兼容,因为它需要不同的数据类型.我还注意到,通常无法将参数传递给OnClick函数.实际上有一种方法可以实现我的建议吗?

However the types are incompatible as it requires a different data type. I also noticed that parameters can't usually be passed into a OnClick function. Is there actually a way of achieving what I have proposed?

这是我当前的创建按钮代码:

This is my current create button code:

function buttonCreate(onClickEvent: TProcedure; 
  left: integer; top: integer; width: integer; height: integer; 
  anchors: TAnchors; caption: string; parent: TWinControl; form: TForm;): TButton;
var
  theButton: TButton;
begin
  theButton := TButton.Create(form);
  theButton.width := width;
  theButton.height := height;
  theButton.left := left;
  theButton.top := top;
  theButton.parent := parent;
  theButton.anchors := anchors;
  //theButton.OnClick := onClickEvent;
  theButton.Caption := caption;
  result := theButton;
end;

任何人和所有帮助表示赞赏!

Any and all help appreciated!

推荐答案

必须准确定义事件处理程序的事件类型定义方式. OnClick事件声明为TNotifyEvent,该事件采用参数(Sender: TObject).您不能违反该规则.

Event handlers must be declared exactly how the event type is defined. An OnClick event is declared as a TNotifyEvent which takes parameters (Sender: TObject). You cannot break that rule.

在这种情况下,您可以将自己的过程包装在事件处理程序中,就像这样...

In your case, you can wrap your own procedure inside of the event handler, like so...

procedure TForm1.Button1Click(Sender: TObject);
begin
  UpdateDatabase(Edit1.text,Edit2.Text,Edit3.Text);
end;

请注意,TNotifyEvent是对象"过程,这意味着必须在对象内部声明事件处理程序.在您的情况下,应在表单内部(而不是在全局位置)声明事件处理程序.

Note that TNotifyEvent is a procedure "of object", which means your event handler must be declared inside of an object. In your case, the event handler should be declared inside your form (not in a global location).

这篇关于在运行时设置Delphi按钮的OnClick过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆