Delphi代码动态创建控件与事件动态绑定

Delphi代码动态创建控件与事件动态绑定

unit MainFrm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TfrmMain = class(TForm)
    btnTest: TButton;
    mmLine: TMemo;
    btnList: TButton;
    btnCreate: TButton;
    procedure btnTestClick(Sender: TObject);
    procedure btnListClick(Sender: TObject);
    procedure btnCreateClick(Sender: TObject);
    procedure btnCateClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  frmMain: TfrmMain;

  type
    TUser = record
    usercode: string;
    username: string;
    usertel: string;
  end;

implementation

{$R *.dfm}

// 按钮事件
procedure TfrmMain.btnCateClick(Sender: TObject);
var
  flag: Integer;
begin
   flag:= (Sender as TButton).Tag;
   ShowMessage('Cate' + IntToStr(flag));
end;

// 测试
procedure TfrmMain.btnCreateClick(Sender: TObject);
var
  btns: TButton;
  i: Integer;
begin
  try
    for i:= 0 to 3 do
    begin
      btns:= TButton.Create(Self);
      btns.Width:= 100;
      btns.Height:= 20;
      btns.Caption:= 'Cate' + IntToStr(i);
      btns.OnClick:= btnCateClick;
      btns.Left:= i * 100;
      btns.Tag:= i;
      btns.Parent:= Self;
    end;
  finally

  end;
end;


end.

 

发表回复

您的电子邮箱地址不会被公开。