unit usLookUpComboBox;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, DB, ADODB, ExtCtrls, StdCtrls;
type
TusLookUpComboBox = class(TComboBox)
private
FGridHeight:Integer; //Grid高度
FGridWidth:Integer; //Grid宽度
FFieldName:string; //字段名(这个属性很重要),就是Text最后得到的字段值
DBGrid:TDBGrid;
FADODataSet: TADODataSet;
DataSource: TDataSource;
procedure GridExit(Sender: TObject); //释放Grid
procedure GridCellClick(Column: TColumn); //点击Grid事件
public
constructor Create(AOwner: TComponent); override; //构造一个 TusComboBox
destructor Destroy; override; //解析 TusComboBox
protected
procedure ComboBoxDropDown(Sender: TObject); //下拉事件
published //这里的 published 是在开发的时候可以设置的属性或者方法
property ADODataSet: TADODataSet read FADODataSet write FADODataSet; //赋ADODataSet属性
property GridHeight:Integer read FGridHeight write FGridHeight; //Grid高度属性
property GridWidth:Integer read FGridWidth write FGridWidth; //Grid宽度属性
property FieldName:string read FFieldName write FFieldName; //字段名属性
end;
procedure Register;
implementation
procedure TusLookUpComboBox.GridExit(Sender: TObject);
begin
DBGrid.Free; //在离开时候释放DBGrid
end;
procedure TusLookUpComboBox.GridCellClick(Column: TColumn);
begin
if (ADODataSet.Active) and (ADODataSet.RecordCount>0) and (ADODataSet.FindField(FieldName)<>nil) then
begin
Self.Text:=ADODataSet.FieldByName(FieldName).AsString; //FieldByName赋予ComboBox的Text
end;
DBGrid.Free;
end;
procedure TusLookUpComboBox.ComboBoxDropDown(Sender: TObject); //下拉事件
begin
DBGrid:=TDBGrid.Create(nil);
//赋予响应事件
DBGrid.OnExit:=GridExit; //离开事件
DBGrid.OnCellClick:=GridCellClick; //点击事件
//调整位置
DBGrid.Top:=Self.top+Self.Height-3;
DBGrid.Left:=Self.Left;
//设置DBGrid的只读属性
DBGrid.Options:=[dgTitles,dgIndicator,dgColumnResize,dgColLines,dgRowLines,dgTabs,dgRowSelect,dgAlwaysShowSelection,dgCancelOnExit];
//打开数据集
ADODataSet.Close;
ADODataSet.Open;
DataSource.DataSet:=ADODataSet;
DBGrid.DataSource:=DataSource;
//显示BGrid
DBGrid.Parent:=Self.Parent;
DBGrid.SetFocus;
end;
constructor TusLookUpComboBox.Create(AOwner: TComponent); //构造一个 TusComboBox
begin
inherited Create(AOwner);
Self.OnDropDown:=ComboBoxDropDown; //赋予下拉事件
ADODataSet:=TADODataSet.Create(nil); //在构造的时候加一个ADODataSet
DataSource:=TDataSource.Create(nil);
end;
destructor TusLookUpComboBox.Destroy; //解析 TusComboBox
begin
DataSource.Free;
ADODataSet.Free;
inherited Destroy;
end;
procedure Register;
begin
RegisterComponents('US', [TusLookUpComboBox]); //在 'US' 的卡中注册 TusLookUpComboBox 这个类
end;
end.
ComboBox下拉DBGrid第三方控件的例子
最新推荐文章于 2023-09-14 10:08:15 发布