Fórum Ajuda criar componente de pesquisa? #393526

09/01/2011

0

Pessoal, estou querendo criar um componente de pesquisa aqui e não estou sabendo como usar o onchange do Edit que esta junto no componente. Tenho uma tabela em access que contem apenas ID (integer) e Campo (varchar 50)

E quero deixar tudo dentro de apenas um componente...

Segue o codigo que estou fazendo

{*******************************************************}
{       Autor:                                          }
{       Adriano Componente Visual                       }
{                                                       }
{  Copyright (c) 2011 - 01 - 09 YYYY=MM+DD              }
{                                                       }
{*******************************************************}
unit uConteinerFilter;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, Math, StdCtrls, Buttons, XPMan, DB, ADODB, Grids, DBGrids,
  ComCtrls;

  const
    {Painel Container}
    cHeigthPanelClient = 523;
    cLeftPanelClient   = 0;
    cTopPanelClient    = 0;
    cWidthPanelClient  = 434;

    {Panel Superior}
    cHeigthPanelTop    = 41;
    cLeftPanelTop      = 0;
    cTopPanelTop       = 0;
    cWidthPanelTop     = 385;

    {Label Pesquisa}
    cLeftLabelPesq     = 10;
    cTopLabelPesq      = 12;

    {Edit Pesquisa}
    cWidthEditPesq     = 257;
    cLeftEditPesq      = 40;
    cTopEditPesq       = 8;

    {Grade de Pesquisa}
    cHeigthGradePesq    = 422;
    cLeftGradePesq      = 0;
    cTopGradePesq       = 43;
    cWidthGradePesq     = 384;

    {Button Filter}
    cHeigthBtFilter    = 25;
    cLeftBtFilter      = 304;
    cTopBtFilter       = 8;
    cWidthBtFilter     = 75;

    {Painel lateral}
    cWidthPanelRigth   = 40;
    cHeigthPanelRigth  = 470;

    
    cHeigthSpeedButton = 33;
    cLeftSeedButton    = 04;
    cTopSeedButton     = 03;
    cWidthSeedButton   = 33;


type
  TContainerFilter = class(TCustomPanel)
  private
    {Componentes de conexão - Utilizei o ADO (dbGo)}
    FsConnection : TADOConnection;
    FsQuery      : TADOQuery;
    FsDataSource : TDataSource;
    //
    FPanelSuperior: TPanel;
    FLabelPesq: TLabel;
    FEditPesq : TEdit;
    FButtonFilter : TButton;
    FGradePesq : TDBGrid;
    FPanelLateral : TPanel;
    FSpeedButton : TSpeedButton;
    FStatusBar: TStatusBar;
    FButtonExit: TNotifyEvent;
    FButtonClick: TNotifyEvent;
    FButtonAutoSize: Boolean;
    FAutoSize: Boolean;
    FEditChange: TNotifyEvent;
    procedure OnSpeedButtonClick(sender: TObject);
    procedure OnSpeedButtonExit(sender: Tobject);
    procedure SetAutoSize(const Value: Boolean);
    procedure SetButtonAutoSize(const Value: Boolean);
    procedure RestrictSize(var msg: TMessage);
    procedure AccessInsensitive(qQuery: TADOQuery; sEdtPesquisa: TEdit;
      TipoFilter: Integer);
    procedure SetEditChange(const Value: TNotifyEvent);
  protected
   //
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    //Propriedades dos eventos do panel
    property OnClick;
    property OnEnter;
    property OnExit;
    property OnDblClick;
    property Parent;
    property Owner;
    property ParentWindow;
    property AutoSize: Boolean read FAutoSize write SetAutoSize default False;
    //Propriedades publicadas SpeedButton
    property OnButtonClick: TNotifyEvent read FButtonClick write FButtonClick;
    property OnButtonExit : TNotifyEvent read FButtonExit write FButtonExit;
    property ButtonAutoSize: Boolean read FButtonAutoSize write SetButtonAutoSize default False;
    property OnEditChange: TNotifyEvent read FEditChange write SetEditChange;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('CompAdriano', [TContainerFilter]);
end;

constructor TContainerFilter.Create(Aowner: TComponent);

  procedure CriarButtons(sCapiton: String; iTop: Integer);
  begin
    FSpeedButton := TSpeedButton.Create(Self);
    with FSpeedButton do {caracteristicas do SpeedButton}
    begin
      Parent    := FPanelLateral;
      Align     := alTop;
      AllowAllUp:= True;

      if GroupIndex = 0 then
        GroupIndex := 1;

    //  Flat := not Flat;
      //
      Left      := cLeftSeedButton;
      Height    := cHeigthSpeedButton;
      Width     := cWidthSeedButton;
      //
      Caption   := sCapiton;
      Font.Name := 'Tahoma';
      Top       := cTopSeedButton + iTop;
      //
      TabOrder  := 0;
      OnClick   := OnSpeedButtonClick;
      OnExit    := OnSpeedButtonExit;
    end;
  end;

begin
  inherited Create(Aowner);
  //Cria os componentes de conexão
  FsConnection := TADOConnection.Create(nil);
  FsQuery := TADOQuery.Create(nil);
  FsDataSource := TDataSource.Create(nil);

  try

    //Tenta abrir a conexão com o banco MDB via aplicativo
    with FsConnection do
    begin
      LoginPrompt := False;
      ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0.;' +
      'Data Source=C:\Access Insensitive\bd1.mdb'; //Passar um arquivo INI aqui
      try
        Connected := True;
      except
        raise exception.Create('O caminho do banco de dados não foi encontrado.');
      end;
    end;

    with FsQuery do
    begin
      Connection := FsConnection;
      AccessInsensitive(FsQuery,FEditPesq,0);
    end;

    with FsDataSource do
    begin
      DataSet := FsQuery;
    end;

    //Montando o painel Cliente (Pai do container)
    Self.Parent := TWinControl(Aowner);
    with Self do
    begin
      Align      := alClient;
      Caption    := EmptyStr;
      Height     := cHeigthPanelClient;
      Top        := cTopPanelClient;
      Left       := cLeftPanelClient;
      Width      := cWidthPanelClient;
      BevelInner := bvNone;
    end;

    FPanelSuperior := TPanel.Create(Self);
    with FPanelSuperior do {caracteristicas do Panel Topo}
    begin
      Parent     := Self;
      //Align      := alTop;
      Font.Name  := 'Tahoma';
      //Font.Style := [fsBold];
      Caption    := EmptyStr;
      Width      := cWidthPanelTop;
      Height     := cHeigthPanelTop;
      BevelInner := bvLowered;
    end;

    FLabelPesq := TLabel.Create(Self);
    with FLabelPesq do {caracteristicas do Label}
    begin
      Caption    := 'Filtro:';
      Parent     := FPanelSuperior;
      Top        := cTopLabelPesq;
      Left       := cLeftLabelPesq;
    end;

    FEditPesq := TEdit.Create(Self);
    with FEditPesq do {caracteristicas do edit}
    begin
      Parent     := FPanelSuperior;
      //Align      := alTop;
      //Font.Name  := 'Tahoma';
      //Font.Style := [fsBold];
      Caption    := EmptyStr;
      Top        := cTopEditPesq;
      Left       := cLeftEditPesq;
      Width      := cWidthEditPesq;
    end;

    FButtonFilter := TButton.Create(Self);
    with FButtonFilter do {caracteristicas do Button}
    begin
      Parent     := FPanelSuperior;
      //Align      := alTop;
      //Font.Name  := 'Tahoma';
      //Font.Style := [fsBold];
      Caption    := 'Filtrar';
      Height     := cHeigthBtFilter;
      Top        := cTopBtFilter;
      Left       := cLeftBtFilter;
      Width      := cWidthBtFilter;
    end;

    FGradePesq := TDBGrid.Create(Self);
    with FGradePesq do {Caracteristica do DBGrid}
    begin
      Parent := Self;
      Height     := cHeigthGradePesq;
      Top        := cTopGradePesq;
      Left       := cLeftGradePesq;
      Width      := cWidthGradePesq;
      DataSource := FsDataSource;
    end;

    FPanelLateral := TPanel.Create(Self);
    with FPanelLateral do {caracteristicas do Panel Lateral}
    begin
      Parent     := Self;
      Align      := alRight;
      Font.Name  := 'Tahoma';
      //Font.Style := [fsBold];
      Caption    := EmptyStr;
      Width      := cWidthPanelRigth;
      Height     := cHeigthPanelRigth;
      BevelInner := bvLowered;
    end;

    //Monta os buttons
    CriarButtons('0..9',0);
    CriarButtons('AB',33);
    CriarButtons('CD',66);
    CriarButtons('EF',99);
    CriarButtons('GH',132);
    CriarButtons('IJ',165);
    CriarButtons('KL',198);
    CriarButtons('MN',231);
    CriarButtons('OP',264);
    CriarButtons('QR',297);
    CriarButtons('ST',330);
    CriarButtons('UV',363);
    CriarButtons('XW',396);
    CriarButtons('YZ',429);

    FStatusBar := TStatusBar.Create(Self);
    with FStatusBar do {caracteristicas do StatusBar}
    begin
      Parent     := Self;
    end;
  finally
    //desalocar da memoria no Destroy
  end;

end;
     
destructor TContainerFilter.Destroy;
begin
  FreeAndNil(FsConnection);
  FreeAndNil(FsQuery);
  FreeAndNil(FsDataSource);
  inherited;
end;

{*****************************************************************************}

procedure TContainerFilter.AccessInsensitive(qQuery: TADOQuery; sEdtPesquisa: TEdit;
  TipoFilter: Integer);
  procedure SelecioneTodos;
  begin
    qQuery.Close;
    qQuery.SQL.Clear;
    qQuery.SQL.Add('SELECT * FROM TABLA ORDER BY CAMPO ');
    qQuery.Open;
  end;
var
 i: Integer;
 str: String;
begin
  str := EmptyStr;
  for i := 1 to Length(sEdtPesquisa.Text) do
    str := str + '_';

  SelecioneTodos;
  //
  if TipoFilter = 0 then // Então o filter é pelo texto no change do Edit (INICIA COM)
  begin
    if sEdtPesquisa.Text <> EmptyStr then
    begin
      qQuery.Close;
      qQuery.SQL.Clear;
      qQuery.SQL.Add(' SELECT * FROM TABLA WHERE (campo BETWEEN :BUSCA_INI AND :BUSCA_FIN) ');
      qQuery.SQL.Add(' AND (campo LIKE :LIMITESPACO) ');
      qQuery.SQL.Add('  OR (campo LIKE :ESCRITEDIT)  ');
      qQuery.SQL.Add('  ORDER BY CAMPO  ');
      qQuery.Parameters.ParamByName('BUSCA_INI').Value :=  FEditPesq.Text;
      qQuery.Parameters.ParamByName('BUSCA_FIN').Value :=  FEditPesq.Text + 'Z'; // Este Z significa um delimitador de caracteres
                                                                                   // para ser contado 1 char a mais depois do STR
      qQuery.Parameters.ParamByName('LIMITESPACO').Value := str +'%';
      qQuery.Parameters.ParamByName('ESCRITEDIT').Value := FEditPesq.Text + '%';
      qQuery.Open;
    end;
  end else
  if TipoFilter = 1 then // Então o filter é o texto do Edit pelo button (CONTENDO)
  begin
    if sEdtPesquisa.Text <> EmptyStr then
    begin
      qQuery.Close;
      qQuery.SQL.Clear;
      qQuery.SQL.Add(' SELECT * FROM TABLA WHERE (campo BETWEEN :BUSCA_INI AND :BUSCA_FIN) ');
      qQuery.SQL.Add(' AND (campo LIKE :LIMITESPACO) ');
      qQuery.SQL.Add('  OR (campo LIKE :ESCRITEDIT)  ');
      qQuery.SQL.Add('  ORDER BY CAMPO  ');
      qQuery.Parameters.ParamByName('BUSCA_INI').Value :=  FEditPesq.Text;
      qQuery.Parameters.ParamByName('BUSCA_FIN').Value :=  FEditPesq.Text + 'Z'; // Este Z significa um delimitador de caracteres
                                                                                   // para ser contado 1 char a mais depois do STR
      qQuery.Parameters.ParamByName('LIMITESPACO').Value := '%'+ str +'%';
      qQuery.Parameters.ParamByName('ESCRITEDIT').Value := '%'+ FEditPesq.Text + '%';
      qQuery.Open;
    end;
  end;
end;

//Metodos SpeedButtons
procedure TContainerFilter.OnSpeedButtonClick(sender: TObject);
begin
  if Assigned(FButtonClick) then
     FButtonClick(Sender);
end;

procedure TContainerFilter.OnSpeedButtonExit(sender: Tobject);
begin
  if Assigned(FButtonExit) then
     FButtonExit(Sender);
end;

procedure TContainerFilter.SetAutoSize(const Value: Boolean);
begin
  if FAutoSize <> Value then
  begin
    FAutoSize := Value;
    if Value then
      AdjustSize; //comando da classe Controls
  end;
end;

procedure TContainerFilter.SetButtonAutoSize(const Value: Boolean);
begin
  if FButtonAutoSize <> Value then
  begin
    FButtonAutoSize := Value;
    if Value then
      AdjustSize; //comando da classe Controls
  end;
end;

procedure TContainerFilter.RestrictSize(var msg: TMessage);
begin
  if (Assigned(FSpeedButton)) then
  begin
    FSpeedButton.Left  := cLeftSeedButton;
    FSpeedButton.Width := (Self.Width div 3)-20;
    Self.Font.Size := Trunc(15 * Self.Height/cHeigthPanelRigth);
  end;
end;

procedure TContainerFilter.SetEditChange(const Value: TNotifyEvent);
begin
  //FEditChange := Value;
  AccessInsensitive(FsQuery,FEditPesq,0);
end;

end.



Ainda falta a parte do click do speedbutton que quero colocar este codigo aqui

procedure FilterLetras(qQuery: TADOQuery; sLetraIni, sLetraFin: String);


begin


  if Trim(EdtPesquisa.Text) <> EmptyStr then


     EdtPesquisa.Clear;


  //


  with qQuery do


  begin


    qQuery.Close;


    qQuery.SQL.Clear;


    qQuery.SQL.Text := ' SELECT * FROM TABLA  WHERE campo LIKE '+ QuotedStr(sLetraIni+'%') +


      'OR campo LIKE ' + QuotedStr(sLetraFin +'%') +


      ' ORDER BY CAMPO ';


    qQuery.Open;


  end;


end;	


E quero chamar no onClick do button assim


procedure SpeedButton1Click(Sender: TObject);


begin


  FilterLetras( ADOQuery1,


                (Sender as TSpeedButton).Caption[1],


                (Sender as TSpeedButton).Caption[2] );


end;




Adriano Dolce

Adriano Dolce

Responder

Posts

09/01/2011

Adriano Dolce

O filter no onClick dos SpeedButons ja consegui resolver, ja o onChange do Edit não deu resultado ainda

Segue...

{*******************************************************}
{       Autor:                                          }
{       Adriano Componente Visual                       }
{                                                       }
{  Copyright (c) 2011 - 01 - 09 YYYY=MM+DD              }
{                                                       }
{*******************************************************}
unit uConteinerFilter;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, Math, StdCtrls, Buttons, XPMan, DB, ADODB, Grids, DBGrids,
  ComCtrls;

  const
    {Painel Container}
    cHeigthPanelClient = 523;
    cLeftPanelClient   = 0;
    cTopPanelClient    = 0;
    cWidthPanelClient  = 434;

    {Panel Superior}
    cHeigthPanelTop    = 41;
    cLeftPanelTop      = 0;
    cTopPanelTop       = 0;
    cWidthPanelTop     = 385;

    {Label Pesquisa}
    cLeftLabelPesq     = 10;
    cTopLabelPesq      = 12;

    {Edit Pesquisa}
    cWidthEditPesq     = 257;
    cLeftEditPesq      = 40;
    cTopEditPesq       = 8;

    {Grade de Pesquisa}
    cHeigthGradePesq    = 422;
    cLeftGradePesq      = 0;
    cTopGradePesq       = 43;
    cWidthGradePesq     = 384;

    {Button Filter}
    cHeigthBtFilter    = 25;
    cLeftBtFilter      = 304;
    cTopBtFilter       = 8;
    cWidthBtFilter     = 75;

    {Painel lateral}
    cWidthPanelRigth   = 40;
    cHeigthPanelRigth  = 470;

    
    cHeigthSpeedButton = 33;
    cLeftSeedButton    = 04;
    cTopSeedButton     = 03;
    cWidthSeedButton   = 33;


type
  TContainerFilter = class(TCustomPanel)
  private
    {Componentes de conexão - Utilizei o ADO (dbGo)}
    FsConnection : TADOConnection;
    FsQuery      : TADOQuery;
    FsDataSource : TDataSource;
    //
    FPanelSuperior: TPanel;
    FLabelPesq: TLabel;
    FEditPesq : TEdit;
    FButtonFilter : TButton;
    FGradePesq : TDBGrid;
    FPanelLateral : TPanel;
    FSpeedButton : TSpeedButton;
    FStatusBar: TStatusBar;
    FButtonExit: TNotifyEvent;
    FButtonClick: TNotifyEvent;
    FButtonAutoSize: Boolean;
    FAutoSize: Boolean;
    FEditExit: TNotifyEvent;
    FEditChange: TNotifyEvent;
    procedure OnSpeedButtonClick(sender: TObject);
    procedure OnSpeedButtonExit(sender: Tobject);
    procedure OnEditChange(sender: TObject);
    procedure OnEditExit(sender: TObject);
    procedure SetAutoSize(const Value: Boolean);
    procedure SetButtonAutoSize(const Value: Boolean);
    procedure RestrictSize(var msg: TMessage);
    procedure AccessInsensitive(qQuery: TADOQuery; sEdtPesquisa: TEdit;
      TipoFilter: Integer);
    procedure FilterLetras(qQuery: TADOQuery; sLetraIni,
      sLetraFin: String);
  protected
   //
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    //Propriedades dos eventos do panel
    property OnClick;
    property OnEnter;
    property OnExit;
    property OnDblClick;
    property Parent;
    property Owner;
    property ParentWindow;
    property AutoSize: Boolean read FAutoSize write SetAutoSize default False;
    //Propriedades publicadas SpeedButton
    property OnButtonClick: TNotifyEvent read FButtonClick write FButtonClick;
    property OnButtonExit : TNotifyEvent read FButtonExit write FButtonExit;
    property EditChange: TNotifyEvent read FEditChange write FEditChange;
    property EditExit: TNotifyEvent read FEditExit write FEditExit;
    property ButtonAutoSize: Boolean read FButtonAutoSize write SetButtonAutoSize default False;

  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('CompAraSystems', [TContainerFilter]);
end;

constructor TContainerFilter.Create(Aowner: TComponent);

  procedure CriarButtons(sCapiton: String; iTop: Integer);
  begin
    FSpeedButton := TSpeedButton.Create(Self);
    with FSpeedButton do {caracteristicas do SpeedButton}
    begin
      Parent    := FPanelLateral;
      Align     := alTop;
      AllowAllUp:= True;

      if GroupIndex = 0 then
        GroupIndex := 1;

    //  Flat := not Flat;
      //
      Left      := cLeftSeedButton;
      Height    := cHeigthSpeedButton;
      Width     := cWidthSeedButton;
      //
      Caption   := sCapiton;
      Font.Name := 'Tahoma';
      Top       := cTopSeedButton + iTop;
      //
      TabOrder  := 0;
      OnClick   := OnSpeedButtonClick;
      OnExit    := OnSpeedButtonExit;
    end;
  end;

begin
  inherited Create(Aowner);
  //Cria os componentes de conexão
  FsConnection := TADOConnection.Create(nil);
  FsQuery := TADOQuery.Create(nil);
  FsDataSource := TDataSource.Create(nil);

  try

    //Tenta abrir a conexão com o banco MDB via aplicativo
    with FsConnection do
    begin
      LoginPrompt := False;
      ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0.;' +
      'Data Source=C:\Access Insensitive\bd1.mdb'; //Passar um arquivo INI aqui
      try
        Connected := True;
      except
        raise exception.Create('O caminho do banco de dados não foi encontrado.');
      end;
    end;

    with FsQuery do
    begin
      Connection := FsConnection;
      AccessInsensitive(FsQuery,FEditPesq,0);
    end;

    with FsDataSource do
    begin
      DataSet := FsQuery;
    end;

    //Montando o painel Cliente (Pai do container)
    Self.Parent := TWinControl(Aowner);
    with Self do
    begin
      Align      := alClient;
      Caption    := EmptyStr;
      Height     := cHeigthPanelClient;
      Top        := cTopPanelClient;
      Left       := cLeftPanelClient;
      Width      := cWidthPanelClient;
      BevelInner := bvNone;
    end;

    FPanelSuperior := TPanel.Create(Self);
    with FPanelSuperior do {caracteristicas do Panel Topo}
    begin
      Parent     := Self;
      //Align      := alTop;
      Font.Name  := 'Tahoma';
      //Font.Style := [fsBold];
      Caption    := EmptyStr;
      Width      := cWidthPanelTop;
      Height     := cHeigthPanelTop;
      BevelInner := bvLowered;
    end;

    FLabelPesq := TLabel.Create(Self);
    with FLabelPesq do {caracteristicas do Label}
    begin
      Caption    := 'Filtro:';
      Parent     := FPanelSuperior;
      Top        := cTopLabelPesq;
      Left       := cLeftLabelPesq;
    end;

    FEditPesq := TEdit.Create(Self);
    with FEditPesq do {caracteristicas do edit}
    begin
      Parent         := FPanelSuperior;
      //Align        := alTop;
      //Font.Name    := 'Tahoma';
      //Font.Style   := [fsBold];
      Caption        := EmptyStr;
      Top            := cTopEditPesq;
      Left           := cLeftEditPesq;
      Width          := cWidthEditPesq;
      OnChange       := EditChange;
      OnExit         := EditExit;
    end;

    FButtonFilter := TButton.Create(Self);
    with FButtonFilter do {caracteristicas do Button}
    begin
      Parent     := FPanelSuperior;
      //Align      := alTop;
      //Font.Name  := 'Tahoma';
      //Font.Style := [fsBold];
      Caption    := 'Filtrar';
      Height     := cHeigthBtFilter;
      Top        := cTopBtFilter;
      Left       := cLeftBtFilter;
      Width      := cWidthBtFilter;
    end;

    FGradePesq := TDBGrid.Create(Self);
    with FGradePesq do {Caracteristica do DBGrid}
    begin
      Parent := Self;
      Height     := cHeigthGradePesq;
      Top        := cTopGradePesq;
      Left       := cLeftGradePesq;
      Width      := cWidthGradePesq;
      DataSource := FsDataSource;
    end;

    FPanelLateral := TPanel.Create(Self);
    with FPanelLateral do {caracteristicas do Panel Lateral}
    begin
      Parent     := Self;
      Align      := alRight;
      Font.Name  := 'Tahoma';
      //Font.Style := [fsBold];
      Caption    := EmptyStr;
      Width      := cWidthPanelRigth;
      Height     := cHeigthPanelRigth;
      BevelInner := bvLowered;
    end;

    //Monta os buttons
    CriarButtons('0..9',0);
    CriarButtons('AB',33);
    CriarButtons('CD',66);
    CriarButtons('EF',99);
    CriarButtons('GH',132);
    CriarButtons('IJ',165);
    CriarButtons('KL',198);
    CriarButtons('MN',231);
    CriarButtons('OP',264);
    CriarButtons('QR',297);
    CriarButtons('ST',330);
    CriarButtons('UV',363);
    CriarButtons('XW',396);
    CriarButtons('YZ',429);

    FStatusBar := TStatusBar.Create(Self);
    with FStatusBar do {caracteristicas do StatusBar}
    begin
      Parent     := Self;
    end;
  finally
    //desalocar da memoria no Destroy
  end;

end;
     
destructor TContainerFilter.Destroy;
begin
  FreeAndNil(FsConnection);
  FreeAndNil(FsQuery);
  FreeAndNil(FsDataSource);
  inherited;
end;

{*****************************************************************************}
procedure TContainerFilter.FilterLetras(qQuery: TADOQuery; sLetraIni, sLetraFin: String);
begin
  if Trim(FEditPesq.Text) <> EmptyStr then
     FEditPesq.Clear;
  //
  with qQuery do
  begin
    qQuery.Close;
    qQuery.SQL.Clear;
    qQuery.SQL.Text := ' SELECT * FROM TABLA  WHERE campo LIKE '+ QuotedStr(sLetraIni+'%') +
      'OR campo LIKE ' + QuotedStr(sLetraFin +'%') +
      ' ORDER BY CAMPO ';
    qQuery.Open;
  end;
end;

procedure TContainerFilter.AccessInsensitive(qQuery: TADOQuery; sEdtPesquisa: TEdit;
  TipoFilter: Integer);
  procedure SelecioneTodos;
  begin
    qQuery.Close;
    qQuery.SQL.Clear;
    qQuery.SQL.Add('SELECT * FROM TABLA ORDER BY CAMPO ');
    qQuery.Open;
  end;
var
 i: Integer;
 str: String;
begin
  str := EmptyStr;
  for i := 1 to Length(sEdtPesquisa.Text) do
    str := str + '_';

  SelecioneTodos;
  //
  if TipoFilter = 0 then // Então o filter é pelo texto no change do Edit (INICIA COM)
  begin
    if sEdtPesquisa.Text <> EmptyStr then
    begin
      qQuery.Close;
      qQuery.SQL.Clear;
      qQuery.SQL.Add(' SELECT * FROM TABLA WHERE (campo BETWEEN :BUSCA_INI AND :BUSCA_FIN) ');
      qQuery.SQL.Add(' AND (campo LIKE :LIMITESPACO) ');
      qQuery.SQL.Add('  OR (campo LIKE :ESCRITEDIT)  ');
      qQuery.SQL.Add('  ORDER BY CAMPO  ');
      qQuery.Parameters.ParamByName('BUSCA_INI').Value :=  FEditPesq.Text;
      qQuery.Parameters.ParamByName('BUSCA_FIN').Value :=  FEditPesq.Text + 'Z'; // Este Z significa um delimitador de caracteres
                                                                                   // para ser contado 1 char a mais depois do STR
      qQuery.Parameters.ParamByName('LIMITESPACO').Value := str +'%';
      qQuery.Parameters.ParamByName('ESCRITEDIT').Value := FEditPesq.Text + '%';
      qQuery.Open;
    end;
  end else
  if TipoFilter = 1 then // Então o filter é o texto do Edit pelo button (CONTENDO)
  begin
    if sEdtPesquisa.Text <> EmptyStr then
    begin
      qQuery.Close;
      qQuery.SQL.Clear;
      qQuery.SQL.Add(' SELECT * FROM TABLA WHERE (campo BETWEEN :BUSCA_INI AND :BUSCA_FIN) ');
      qQuery.SQL.Add(' AND (campo LIKE :LIMITESPACO) ');
      qQuery.SQL.Add('  OR (campo LIKE :ESCRITEDIT)  ');
      qQuery.SQL.Add('  ORDER BY CAMPO  ');
      qQuery.Parameters.ParamByName('BUSCA_INI').Value :=  FEditPesq.Text;
      qQuery.Parameters.ParamByName('BUSCA_FIN').Value :=  FEditPesq.Text + 'Z'; // Este Z significa um delimitador de caracteres
                                                                                   // para ser contado 1 char a mais depois do STR
      qQuery.Parameters.ParamByName('LIMITESPACO').Value := '%'+ str +'%';
      qQuery.Parameters.ParamByName('ESCRITEDIT').Value := '%'+ FEditPesq.Text + '%';
      qQuery.Open;
    end;
  end;
end;

//Metodos SpeedButtons
procedure TContainerFilter.OnSpeedButtonClick(sender: TObject);
begin
  if Assigned(FButtonClick) then
     FilterLetras( FsQuery,
                (Sender as TSpeedButton).Caption[1],
                (Sender as TSpeedButton).Caption[2] );
end;

procedure TContainerFilter.OnSpeedButtonExit(sender: Tobject);
begin
  if Assigned(FButtonExit) then
     FButtonExit(Sender);
end;

procedure TContainerFilter.SetAutoSize(const Value: Boolean);
begin
  if FAutoSize <> Value then
  begin
    FAutoSize := Value;
    if Value then
      AdjustSize; //comando da classe Controls
  end;
end;

procedure TContainerFilter.SetButtonAutoSize(const Value: Boolean);
begin
  if FButtonAutoSize <> Value then
  begin
    FButtonAutoSize := Value;
    if Value then
      AdjustSize; //comando da classe Controls
  end;
end;

procedure TContainerFilter.RestrictSize(var msg: TMessage);
begin
  if (Assigned(FSpeedButton)) then
  begin
    FSpeedButton.Left  := cLeftSeedButton;
    FSpeedButton.Width := (Self.Width div 3)-20;
    Self.Font.Size := Trunc(15 * Self.Height/cHeigthPanelRigth);
  end;
end;

procedure TContainerFilter.OnEditChange(sender: TObject);
begin
  if Assigned(FEditChange) then
    AccessInsensitive(FsQuery,FEditPesq,0);
end;

procedure TContainerFilter.OnEditExit(sender: TObject);
begin
  if Assigned(FEditExit) then
     FEditExit(Sender);
end;

end.



Estou chamando assim no form

procedure TForm1.ContainerFilter1EditChange(Sender: TObject);
var
  Acesso: TContainerFilter;
begin
  Acesso := TContainerFilter.Create(Self);
  Acesso.EditChange(Sender);
end;

procedure TForm1.ContainerFilter1ButtonClick(Sender: TObject);
var
  Acesso: TContainerFilter;
begin
  Acesso := TContainerFilter.Create(Self);
  Acesso.OnButtonClick(Sender);
end;





Responder

Gostei + 0

09/01/2011

Adriano Dolce

Esqueçe o post pessoal...  Foi burrada minha... Eu estava setando errado os eventos.

Resolvido esta parte do componente...

{*******************************************************}
{       Autor:                                          }
{       Adriano Componente Visual                       }
{                                                       }
{  Copyright (c) 2011 - 01 - 09 YYYY=MM+DD              }
{                                                       }
{*******************************************************}
unit uConteinerFilter;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, Math, StdCtrls, Buttons, XPMan, DB, ADODB, Grids, DBGrids,
  ComCtrls;

  const
    {Painel Container}
    cHeigthPanelClient = 523;
    cLeftPanelClient   = 0;
    cTopPanelClient    = 0;
    cWidthPanelClient  = 434;

    {Panel Superior}
    cHeigthPanelTop    = 41;
    cLeftPanelTop      = 0;
    cTopPanelTop       = 0;
    cWidthPanelTop     = 385;

    {Label Pesquisa}
    cLeftLabelPesq     = 10;
    cTopLabelPesq      = 12;

    {Edit Pesquisa}
    cWidthEditPesq     = 257;
    cLeftEditPesq      = 40;
    cTopEditPesq       = 8;

    {Grade de Pesquisa}
    cHeigthGradePesq    = 422;
    cLeftGradePesq      = 0;
    cTopGradePesq       = 43;
    cWidthGradePesq     = 384;

    {Button Filter}
    cHeigthBtFilter    = 25;
    cLeftBtFilter      = 304;
    cTopBtFilter       = 8;
    cWidthBtFilter     = 75;

    {Painel lateral}
    cWidthPanelRigth   = 40;
    cHeigthPanelRigth  = 470;

    
    cHeigthSpeedButton = 33;
    cLeftSeedButton    = 04;
    cTopSeedButton     = 03;
    cWidthSeedButton   = 33;


type
  TContainerFilter = class(TCustomPanel)
  private
    {Componentes de conexão - Utilizei o ADO (dbGo)}
    FsConnection : TADOConnection;
    FsQuery      : TADOQuery;
    FsDataSource : TDataSource;
    //
    FPanelSuperior: TPanel;
    FLabelPesq: TLabel;
    FEditPesq : TEdit;
    FButtonFilter : TButton;
    FGradePesq : TDBGrid;
    FPanelLateral : TPanel;
    FSpeedButton : TSpeedButton;
    FStatusBar: TStatusBar;
    FButtonExit: TNotifyEvent;
    FButtonClick: TNotifyEvent;
    FButtonAutoSize: Boolean;
    FAutoSize: Boolean;
    FEditExit: TNotifyEvent;
    FEditChange: TNotifyEvent;
    FBitBtnClick: TNotifyEvent;
    procedure OnSpeedButtonClick(sender: TObject);
    procedure OnSpeedButtonExit(sender: Tobject);
    procedure OnEditChange(sender: TObject);
    procedure OnEditExit(sender: TObject);
    procedure OnBitBtn(sender: TObject);
    procedure SetAutoSize(const Value: Boolean);
    procedure SetButtonAutoSize(const Value: Boolean);
    procedure RestrictSize(var msg: TMessage);
    procedure AccessInsensitive(qQuery: TADOQuery; sEdtPesquisa: TEdit;
      TipoFilter: Integer);
    procedure FilterLetras(qQuery: TADOQuery; sLetraIni,
      sLetraFin: String);
  protected
   //
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    //Propriedades dos eventos do panel
    property OnClick;
    property OnEnter;
    property OnExit;
    property OnDblClick;
    property Parent;
    property Owner;
    property ParentWindow;
    property AutoSize: Boolean read FAutoSize write SetAutoSize default False;
    //Propriedades publicadas SpeedButton
    property OnButtonClick: TNotifyEvent read FButtonClick write FButtonClick;
    property OnButtonExit : TNotifyEvent read FButtonExit write FButtonExit;
    property EditChange: TNotifyEvent read FEditChange write FEditChange;
    property EditExit: TNotifyEvent read FEditExit write FEditExit;
    property OnBitBtnClick: TNotifyEvent read FBitBtnClick write FBitBtnClick;
    property ButtonAutoSize: Boolean read FButtonAutoSize write SetButtonAutoSize default False;

  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('CompAraSystems', [TContainerFilter]);
end;

constructor TContainerFilter.Create(Aowner: TComponent);

  procedure CriarButtons(sCapiton: String; iTop: Integer);
  begin
    FSpeedButton := TSpeedButton.Create(Self);
    with FSpeedButton do {caracteristicas do SpeedButton}
    begin
      Parent    := FPanelLateral;
      Align     := alTop;
      AllowAllUp:= True;

      if GroupIndex = 0 then
        GroupIndex := 1;

    //  Flat := not Flat;
      //
      Left      := cLeftSeedButton;
      Height    := cHeigthSpeedButton;
      Width     := cWidthSeedButton;
      //
      Caption   := sCapiton;
      Font.Name := 'Tahoma';
      Top       := cTopSeedButton + iTop;
      //
      TabOrder  := 0;
      OnClick   := OnSpeedButtonClick;
      OnExit    := OnSpeedButtonExit;
    end;
  end;

begin
  inherited Create(Aowner);
  //Cria os componentes de conexão
  FsConnection := TADOConnection.Create(nil);
  FsQuery := TADOQuery.Create(nil);
  FsDataSource := TDataSource.Create(nil);

  try

    //Tenta abrir a conexão com o banco MDB via aplicativo
    with FsConnection do
    begin
      LoginPrompt := False;
      ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0.;' +
      'Data Source=C:\Access Insensitive\bd1.mdb'; //Passar um arquivo INI aqui
      try
        Connected := True;
      except
        raise exception.Create('O caminho do banco de dados não foi encontrado.');
      end;
    end;

    with FsQuery do
    begin
      Connection := FsConnection;
      AccessInsensitive(FsQuery,FEditPesq,0);
    end;

    with FsDataSource do
    begin
      DataSet := FsQuery;
    end;

    //Montando o painel Cliente (Pai do container)
    Self.Parent := TWinControl(Aowner);
    with Self do
    begin
      Align      := alClient;
      Caption    := EmptyStr;
      Height     := cHeigthPanelClient;
      Top        := cTopPanelClient;
      Left       := cLeftPanelClient;
      Width      := cWidthPanelClient;
      BevelInner := bvNone;
    end;

    FPanelSuperior := TPanel.Create(Self);
    with FPanelSuperior do {caracteristicas do Panel Topo}
    begin
      Parent     := Self;
      //Align      := alTop;
      Font.Name  := 'Tahoma';
      //Font.Style := [fsBold];
      Caption    := EmptyStr;
      Width      := cWidthPanelTop;
      Height     := cHeigthPanelTop;
      BevelInner := bvLowered;
    end;

    FLabelPesq := TLabel.Create(Self);
    with FLabelPesq do {caracteristicas do Label}
    begin
      Caption    := 'Filtro:';
      Parent     := FPanelSuperior;
      Top        := cTopLabelPesq;
      Left       := cLeftLabelPesq;
    end;

    FEditPesq := TEdit.Create(Self);
    with FEditPesq do {caracteristicas do edit}
    begin
      Parent         := FPanelSuperior;
      //Align        := alTop;
      //Font.Name    := 'Tahoma';
      //Font.Style   := [fsBold];
      Caption        := EmptyStr;
      Top            := cTopEditPesq;
      Left           := cLeftEditPesq;
      Width          := cWidthEditPesq;
      OnChange       := OnEditChange;
      OnExit         := OnEditExit;
    end;

    FButtonFilter := TBitBtn.Create(Self);
    with FButtonFilter do {caracteristicas do Button}
    begin
      Parent     := FPanelSuperior;
      //Align      := alTop;
      //Font.Name  := 'Tahoma';
      //Font.Style := [fsBold];
      Caption    := 'Filtrar';
      Height     := cHeigthBtFilter;
      Top        := cTopBtFilter;
      Left       := cLeftBtFilter;
      Width      := cWidthBtFilter;
      OnClick    := OnBitBtn;
    end;

    FGradePesq := TDBGrid.Create(Self);
    with FGradePesq do {Caracteristica do DBGrid}
    begin
      Parent := Self;
      Height     := cHeigthGradePesq;
      Top        := cTopGradePesq;
      Left       := cLeftGradePesq;
      Width      := cWidthGradePesq;
      DataSource := FsDataSource;
    end;

    FPanelLateral := TPanel.Create(Self);
    with FPanelLateral do {caracteristicas do Panel Lateral}
    begin
      Parent     := Self;
      Align      := alRight;
      Font.Name  := 'Tahoma';
      //Font.Style := [fsBold];
      Caption    := EmptyStr;
      Width      := cWidthPanelRigth;
      Height     := cHeigthPanelRigth;
      BevelInner := bvLowered;
    end;

    //Monta os buttons
    CriarButtons('0..9',0);
    CriarButtons('AB',33);
    CriarButtons('CD',66);
    CriarButtons('EF',99);
    CriarButtons('GH',132);
    CriarButtons('IJ',165);
    CriarButtons('KL',198);
    CriarButtons('MN',231);
    CriarButtons('OP',264);
    CriarButtons('QR',297);
    CriarButtons('ST',330);
    CriarButtons('UV',363);
    CriarButtons('XW',396);
    CriarButtons('YZ',429);

    FStatusBar := TStatusBar.Create(Self);
    with FStatusBar do {caracteristicas do StatusBar}
    begin
      Parent     := Self;
    end;
  finally
    //desalocar da memoria no Destroy
  end;

end;
     
destructor TContainerFilter.Destroy;
begin
  FreeAndNil(FsConnection);
  FreeAndNil(FsQuery);
  FreeAndNil(FsDataSource);
  inherited;
end;

{*****************************************************************************}
procedure TContainerFilter.FilterLetras(qQuery: TADOQuery; sLetraIni, sLetraFin: String);
begin
  if Trim(FEditPesq.Text) <> EmptyStr then
     FEditPesq.Clear;
  //
  with qQuery do
  begin
    qQuery.Close;
    qQuery.SQL.Clear;
    qQuery.SQL.Text := ' SELECT * FROM TABLA  WHERE campo LIKE '+ QuotedStr(sLetraIni+'%') +
      'OR campo LIKE ' + QuotedStr(sLetraFin +'%') +
      ' ORDER BY CAMPO ';
    qQuery.Open;
  end;
end;

procedure TContainerFilter.AccessInsensitive(qQuery: TADOQuery; sEdtPesquisa: TEdit;
  TipoFilter: Integer);
  procedure SelecioneTodos;
  begin
    qQuery.Close;
    qQuery.SQL.Clear;
    qQuery.SQL.Add('SELECT * FROM TABLA ORDER BY CAMPO ');
    qQuery.Open;
  end;
var
 i: Integer;
 str: String;
begin
  str := EmptyStr;
  for i := 1 to Length(sEdtPesquisa.Text) do
    str := str + '_';

  SelecioneTodos;
  //
  if TipoFilter = 0 then // Então o filter é pelo texto no change do Edit (INICIA COM)
  begin
    if sEdtPesquisa.Text <> EmptyStr then
    begin
      qQuery.Close;
      qQuery.SQL.Clear;
      qQuery.SQL.Add(' SELECT * FROM TABLA WHERE (campo BETWEEN :BUSCA_INI AND :BUSCA_FIN) ');
      qQuery.SQL.Add(' AND (campo LIKE :LIMITESPACO) ');
      qQuery.SQL.Add('  OR (campo LIKE :ESCRITEDIT)  ');
      qQuery.SQL.Add('  ORDER BY CAMPO  ');
      qQuery.Parameters.ParamByName('BUSCA_INI').Value :=  FEditPesq.Text;
      qQuery.Parameters.ParamByName('BUSCA_FIN').Value :=  FEditPesq.Text + 'Z'; // Este Z significa um delimitador de caracteres
                                                                                   // para ser contado 1 char a mais depois do STR
      qQuery.Parameters.ParamByName('LIMITESPACO').Value := str +'%';
      qQuery.Parameters.ParamByName('ESCRITEDIT').Value := FEditPesq.Text + '%';
      qQuery.Open;
    end;
  end else
  if TipoFilter = 1 then // Então o filter é o texto do Edit pelo button (CONTENDO)
  begin
    if sEdtPesquisa.Text <> EmptyStr then
    begin
      qQuery.Close;
      qQuery.SQL.Clear;
      qQuery.SQL.Add(' SELECT * FROM TABLA WHERE (campo BETWEEN :BUSCA_INI AND :BUSCA_FIN) ');
      qQuery.SQL.Add(' AND (campo LIKE :LIMITESPACO) ');
      qQuery.SQL.Add('  OR (campo LIKE :ESCRITEDIT)  ');
      qQuery.SQL.Add('  ORDER BY CAMPO  ');
      qQuery.Parameters.ParamByName('BUSCA_INI').Value :=  FEditPesq.Text;
      qQuery.Parameters.ParamByName('BUSCA_FIN').Value :=  FEditPesq.Text + 'Z'; // Este Z significa um delimitador de caracteres
                                                                                   // para ser contado 1 char a mais depois do STR
      qQuery.Parameters.ParamByName('LIMITESPACO').Value := '%'+ str +'%';
      qQuery.Parameters.ParamByName('ESCRITEDIT').Value := '%'+ FEditPesq.Text + '%';
      qQuery.Open;
    end;
  end;
end;

procedure TContainerFilter.OnEditChange(sender: TObject);
begin
  if Assigned(FEditChange) then
    AccessInsensitive(FsQuery,FEditPesq,0);
end;

procedure TContainerFilter.OnEditExit(sender: TObject);
begin
  if Assigned(FEditExit) then
     FEditExit(Sender);
end;

procedure TContainerFilter.OnBitBtn(sender: TObject);
begin
  if Assigned(FBitBtnClick) then
  begin
    Tag := 1;
    AccessInsensitive(FsQuery,FEditPesq,1);
  end;   
end;

//Metodos SpeedButtons
procedure TContainerFilter.OnSpeedButtonClick(sender: TObject);
begin
  if Assigned(FButtonClick) then
     FilterLetras( FsQuery,
                (Sender as TSpeedButton).Caption[1],
                (Sender as TSpeedButton).Caption[2] );
end;

procedure TContainerFilter.OnSpeedButtonExit(sender: Tobject);
begin
  if Assigned(FButtonExit) then
     FButtonExit(Sender);
end;

procedure TContainerFilter.SetAutoSize(const Value: Boolean);
begin
  if FAutoSize <> Value then
  begin
    FAutoSize := Value;
    if Value then
      AdjustSize; //comando da classe Controls
  end;
end;

procedure TContainerFilter.SetButtonAutoSize(const Value: Boolean);
begin
  if FButtonAutoSize <> Value then
  begin
    FButtonAutoSize := Value;
    if Value then
      AdjustSize; //comando da classe Controls
  end;
end;

procedure TContainerFilter.RestrictSize(var msg: TMessage);
begin
  if (Assigned(FSpeedButton)) then
  begin
    FSpeedButton.Left  := cLeftSeedButton;
    FSpeedButton.Width := (Self.Width div 3)-20;
    Self.Font.Size := Trunc(15 * Self.Height/cHeigthPanelRigth);
  end;
end;

end.


Chamo assim no form
procedure TForm1.ContainerFilter1EditChange(Sender: TObject);
var
  Acesso: TContainerFilter;
begin
  Acesso := TContainerFilter.Create(Self);
  Acesso.EditChange(Sender);
end;

procedure TForm1.ContainerFilter1ButtonClick(Sender: TObject);
var
  Acesso: TContainerFilter;
begin
  Acesso := TContainerFilter.Create(Self);
  Acesso.OnButtonClick(Sender);
end;

procedure TForm1.ContainerFilter1BitBtnClick(Sender: TObject);
var
  Acesso: TContainerFilter;
begin
  Acesso := TContainerFilter.Create(Self);
  Acesso.OnBitBtnClick(Sender);
end;


Bom, neste componente ai existe varios speedbuttons lateral direito, e esta vindo em negrito... Gostaria de saber se tem como deixar estes speedbuttons da lateral com fonte normal.

Esta é a duvida agora.


Se alguem quiser me ajudar, segue o link contendo o componente (PAS, DCU + MDB) o banco em access que fiz.
http://www.4shared.com/file/IaTWZr2v/CompFilter.html

O caminho do banco ainda não fiz, então esta fixo o local
'Data Source=C:\Access Insensitive\bd1.mdb'; //Passar um arquivo INI aqui

Mais se quiserem mudar o local do banco, basta mudar no componente também.

Quero deixar claro também que depois que estiver pronto, esta parte quero ver uma forma de fazer esta conexão mais generica, e logico o select não pode ficar fixo como esta ai aponetado para uma table, mais isso vou fazer na sequência.


Obrigado.



Responder

Gostei + 0

10/01/2011

Leonardo Xavier

ola você ja resolveu este post?
Responder

Gostei + 0

10/01/2011

Adriano Dolce

ola você ja resolveu este post?
Ainda não... não consigo retirar o negrito dos speedbuttons laterais....   Obrigado...
Responder

Gostei + 0

10/01/2011

Wilson Junior

Coloque o a propriedade ParentFont do SpeedButton como False.

Espero ter colaborado.
Responder

Gostei + 0

10/01/2011

Adriano Dolce

Ola amigo, coloquei o que foi solicitado no construtor veja...
constructor TContainerFilter.Create(Aowner: TComponent);

  procedure CriarButtons(sCapiton: String; iTop: Integer);
  begin
    FSpeedButton := TSpeedButton.Create(Self);
    with FSpeedButton do {caracteristicas do SpeedButton}
    begin
      Parent    := FPanelLateral;
      Align     := alTop;
      AllowAllUp:= True;

      if GroupIndex = 0 then
        GroupIndex := 1;

    //  Flat := not Flat;
      //
      Left      := cLeftSeedButton;
      Height    := cHeigthSpeedButton;
      Width     := cWidthSeedButton;
      //
      ParentFont:= False;
      Caption   := sCapiton;
      Font.Name := 'Tahoma';
      Font.Size := 8;
      Top       := cTopSeedButton + iTop;
      //
      TabOrder  := 0;
      OnClick   := OnSpeedButtonClick;
      OnExit    := OnSpeedButtonExit;
    end;
  end;


Mais não deu certo ainda... veja imagem
http://666kb.com/i/bpzysib2r55zwmk4e.gif






Responder

Gostei + 0

11/01/2011

Wilson Junior

Atribua ao seu FPanelLateral o ParentFont como False.

Espero ter colaborado.

Responder

Gostei + 0

11/01/2011

Adriano Dolce

Atribua ao seu FPanelLateral o ParentFont como False.

Espero ter colaborado.

Ainda não consegui amigo... Veja como esta agora o componente todo

{*******************************************************}
{       Autor: Adriano -  Componente Visual             }
{   Componente para filtrar banco de dados              }
{   Para chamar o componente no form basta chamar o     }
{ SENDER Ex:                                            }
{       var                                             }
{         Acesso: TContainerFilter;                     }
{       begin                                           }
{         Acesso := TContainerFilter.Create(Self);      }
{         Acesso.EditChange(Sender);                    }
{       end;                                            }
{ O mesmo para os outros                                }
{             OnButtonClick(Sender)                     }
{             OnBitBtnClick(Sender)                     }
{                                                       }
{  Copyright (c) 2011 - 01 - 09 YYYY=MM+DD              }
{*******************************************************}
unit uConteinerFilter;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, Math, StdCtrls, Buttons, XPMan, DB, ADODB, Grids, DBGrids,
  ComCtrls;

  const
    {Painel Container}
    cHeigthPanelClient = 523;
    cLeftPanelClient   = 0;
    cTopPanelClient    = 0;
    cWidthPanelClient  = 434;

    {Panel Superior}
    cHeigthPanelTop    = 41;
    cLeftPanelTop      = 0;
    cTopPanelTop       = 0;
    cWidthPanelTop     = 385;

    {Label Pesquisa}
    cLeftLabelPesq     = 10;
    cTopLabelPesq      = 12;

    {Edit Pesquisa}
    cWidthEditPesq     = 257;
    cLeftEditPesq      = 40;
    cTopEditPesq       = 8;

    {Grade de Pesquisa}
    cHeigthGradePesq    = 422;
    cLeftGradePesq      = 0;
    cTopGradePesq       = 43;
    cWidthGradePesq     = 384;

    {Button Filter}
    cHeigthBtFilter    = 25;
    cLeftBtFilter      = 304;
    cTopBtFilter       = 8;
    cWidthBtFilter     = 75;

    {Painel lateral}
    cWidthPanelRigth   = 40;
    cHeigthPanelRigth  = 470;

    
    cHeigthSpeedButton = 33;
    cLeftSeedButton    = 04;
    cTopSeedButton     = 03;
    cWidthSeedButton   = 33;

type
  TContainerFilter = class(TCustomPanel)
  private
    {Componentes de conexão - Utilizei o ADO (dbGo)}
    FsConnection : TADOConnection;
    FsQuery      : TADOQuery;
    FsDataSource : TDataSource;
    //
    FPanelSuperior: TPanel;
    FLabelPesq: TLabel;
    FEditPesq : TEdit;
    FButtonFilter : TButton;
    FGradePesq : TDBGrid;
    FPanelLateral : TPanel;
    FSpeedButton : TSpeedButton;
    FStatusBar: TStatusBar;
    FButtonExit: TNotifyEvent;
    FButtonClick: TNotifyEvent;
    FButtonAutoSize: Boolean;
    FAutoSize: Boolean;
    FEditExit: TNotifyEvent;
    FEditChange: TNotifyEvent;
    FBitBtnClick: TNotifyEvent;
    procedure OnSpeedButtonClick(sender: TObject);
    procedure OnSpeedButtonExit(sender: Tobject);
    procedure OnEditChange(sender: TObject);
    procedure OnEditExit(sender: TObject);
    procedure OnBitBtn(sender: TObject);
    procedure SetAutoSize(const Value: Boolean);
    procedure SetButtonAutoSize(const Value: Boolean);
    procedure RestrictSize(var msg: TMessage);
    procedure AccessInsensitive(qQuery: TADOQuery; sEdtPesquisa: TEdit;
      TipoFilter: Integer);
    procedure FilterLetras(qQuery: TADOQuery; sLetraIni,
      sLetraFin: String);
  protected
   //
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    //Propriedades dos eventos do panel
    property OnClick;
    property OnEnter;
    property OnExit;
    property OnDblClick;
    property Parent;
    property Owner;
    property ParentWindow;
    property AutoSize: Boolean read FAutoSize write SetAutoSize default False;
    //Propriedades publicadas SpeedButton
    property OnButtonClick: TNotifyEvent read FButtonClick write FButtonClick;
    property OnButtonExit : TNotifyEvent read FButtonExit write FButtonExit;
    property EditChange: TNotifyEvent read FEditChange write FEditChange;
    property EditExit: TNotifyEvent read FEditExit write FEditExit;
    property OnBitBtnClick: TNotifyEvent read FBitBtnClick write FBitBtnClick;
    property ButtonAutoSize: Boolean read FButtonAutoSize write SetButtonAutoSize default False;

  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('CompAraSystems', [TContainerFilter]);
end;

constructor TContainerFilter.Create(Aowner: TComponent);

  procedure CriarButtons(sCapiton: String; iTop: Integer);
  begin
    FSpeedButton := TSpeedButton.Create(Self);
    with FSpeedButton do {caracteristicas do SpeedButton}
    begin
      Parent    := FPanelLateral;
      Align     := alTop;
      AllowAllUp:= True;

      if GroupIndex = 0 then
        GroupIndex := 1;

    //  Flat := not Flat;
      //
      Left      := cLeftSeedButton;
      Height    := cHeigthSpeedButton;
      Width     := cWidthSeedButton;
      //
      ParentFont:= False;
      Caption   := sCapiton;
      Font.Name := 'Tahoma';
      Font.Size := 8;
      Top       := cTopSeedButton + iTop;
      //
      TabOrder  := 0;
      OnClick   := OnSpeedButtonClick;
      OnExit    := OnSpeedButtonExit;
    end;
  end;

begin
  inherited Create(Aowner);
  //Cria os componentes de conexão
  FsConnection := TADOConnection.Create(nil);
  FsQuery := TADOQuery.Create(nil);
  FsDataSource := TDataSource.Create(nil);

  try

    //Tenta abrir a conexão com o banco MDB via aplicativo
    with FsConnection do
    begin
      LoginPrompt := False;
      ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0.;' +
      'Data Source=C:\Access Insensitive\bd1.mdb'; //Passar um arquivo INI aqui
      try
        Connected := True;
      except
        raise exception.Create('O caminho do banco de dados não foi encontrado.');
      end;
    end;

    with FsQuery do
    begin
      Connection := FsConnection;
      AccessInsensitive(FsQuery,FEditPesq,0);
    end;

    with FsDataSource do
    begin
      DataSet := FsQuery;
    end;

    //Montando o painel Cliente (Pai do container)
    Self.Parent := TWinControl(Aowner);
    with Self do
    begin
      Align      := alClient;
      Caption    := EmptyStr;
      Height     := cHeigthPanelClient;
      Top        := cTopPanelClient;
      Left       := cLeftPanelClient;
      Width      := cWidthPanelClient;
      BevelInner := bvNone;
    end;

    FPanelSuperior := TPanel.Create(Self);
    with FPanelSuperior do {caracteristicas do Panel Topo}
    begin
      Parent     := Self;
      Font.Name  := 'Tahoma';
      Font.Size  := 8;
      Caption    := EmptyStr;
      Width      := cWidthPanelTop;
      Height     := cHeigthPanelTop;
      BevelInner := bvLowered;
    end;

    FLabelPesq := TLabel.Create(Self);
    with FLabelPesq do {caracteristicas do Label}
    begin
      Caption    := 'Filtro:';
      Parent     := FPanelSuperior;
      Top        := cTopLabelPesq;
      Left       := cLeftLabelPesq;
    end;

    FEditPesq := TEdit.Create(Self);
    with FEditPesq do {caracteristicas do edit}
    begin
      Parent         := FPanelSuperior;
      //Align        := alTop;
      //Font.Name    := 'Tahoma';
      //Font.Style   := [fsBold];
      Caption        := EmptyStr;
      Top            := cTopEditPesq;
      Left           := cLeftEditPesq;
      Width          := cWidthEditPesq;
      OnChange       := OnEditChange;
      OnExit         := OnEditExit;
    end;

    FButtonFilter := TBitBtn.Create(Self);
    with FButtonFilter do {caracteristicas do Button}
    begin
      Parent     := FPanelSuperior;
      //Align      := alTop;
      //Font.Name  := 'Tahoma';
      //Font.Style := [fsBold];
      Caption    := 'Filtrar';
      Height     := cHeigthBtFilter;
      Top        := cTopBtFilter;
      Left       := cLeftBtFilter;
      Width      := cWidthBtFilter;
      OnClick    := OnBitBtn;
    end;

    FGradePesq := TDBGrid.Create(Self);
    with FGradePesq do {Caracteristica do DBGrid}
    begin
      Parent := Self;
      Height     := cHeigthGradePesq;
      Top        := cTopGradePesq;
      Left       := cLeftGradePesq;
      Width      := cWidthGradePesq;
      DataSource := FsDataSource;
    end;

    FPanelLateral := TPanel.Create(Self);
    with FPanelLateral do {caracteristicas do Panel Lateral}
    begin
      Parent     := Self;
      Align      := alRight;
      ParentFont:= False;
      Font.Name  := 'Tahoma';
      Font.Size  := 8;
      Caption    := EmptyStr;
      Width      := cWidthPanelRigth;
      Height     := cHeigthPanelRigth;
      BevelInner := bvLowered;
    end;

    //Monta os buttons
    CriarButtons('0..9',0);
    CriarButtons('AB',33);
    CriarButtons('CD',66);
    CriarButtons('EF',99);
    CriarButtons('GH',132);
    CriarButtons('IJ',165);
    CriarButtons('KL',198);
    CriarButtons('MN',231);
    CriarButtons('OP',264);
    CriarButtons('QR',297);
    CriarButtons('ST',330);
    CriarButtons('UV',363);
    CriarButtons('XW',396);
    CriarButtons('YZ',429);

    FStatusBar := TStatusBar.Create(Self);
    with FStatusBar do {caracteristicas do StatusBar}
    begin
      Parent     := Self;
    end;
  finally
    //desalocar da memoria no Destroy
  end;

end;
     
destructor TContainerFilter.Destroy;
begin
  FreeAndNil(FsConnection);
  FreeAndNil(FsQuery);
  FreeAndNil(FsDataSource);
  inherited;
end;

{*****************************************************************************}
procedure TContainerFilter.FilterLetras(qQuery: TADOQuery; sLetraIni, sLetraFin: String);
begin
  if Trim(FEditPesq.Text) <> EmptyStr then
     FEditPesq.Clear;
  //
  with qQuery do
  begin
    qQuery.Close;
    qQuery.SQL.Clear;
    qQuery.SQL.Text := ' SELECT * FROM TABLA  WHERE campo LIKE '+ QuotedStr(sLetraIni+'%') +
      ' OR campo LIKE ' + QuotedStr(sLetraFin +'%') +
      ' ORDER BY CAMPO ';
    qQuery.Open;
  end;
end;

procedure TContainerFilter.AccessInsensitive(qQuery: TADOQuery; sEdtPesquisa: TEdit;
  TipoFilter: Integer);
  procedure SelecioneTodos;
  begin
    qQuery.Close;
    qQuery.SQL.Clear;
    qQuery.SQL.Add('SELECT * FROM TABLA ORDER BY CAMPO ');
    qQuery.Open;
  end;
var
 i: Integer;
 str: String;
begin
  str := EmptyStr;
  for i := 1 to Length(sEdtPesquisa.Text) do
    str := str + '_';

  SelecioneTodos;
  //
  if TipoFilter = 0 then // Então o filter é pelo texto no change do Edit (INICIA COM)
  begin
    if sEdtPesquisa.Text <> EmptyStr then
    begin
      qQuery.Close;
      qQuery.SQL.Clear;
      qQuery.SQL.Add(' SELECT * FROM TABLA WHERE (campo BETWEEN :BUSCA_INI AND :BUSCA_FIN) ');
      qQuery.SQL.Add(' AND (campo LIKE :LIMITESPACO) ');
      qQuery.SQL.Add('  OR (campo LIKE :ESCRITEDIT)  ');
      qQuery.SQL.Add('  ORDER BY CAMPO  ');
      qQuery.Parameters.ParamByName('BUSCA_INI').Value :=  FEditPesq.Text;
      qQuery.Parameters.ParamByName('BUSCA_FIN').Value :=  FEditPesq.Text + 'Z'; // Este Z significa um delimitador de caracteres
                                                                                   // para ser contado 1 char a mais depois do STR
      qQuery.Parameters.ParamByName('LIMITESPACO').Value := str +'%';
      qQuery.Parameters.ParamByName('ESCRITEDIT').Value := FEditPesq.Text + '%';
      qQuery.Open;
    end;
  end else
  if TipoFilter = 1 then // Então o filter é o texto do Edit pelo button (CONTENDO)
  begin
    if sEdtPesquisa.Text <> EmptyStr then
    begin
      qQuery.Close;
      qQuery.SQL.Clear;
      qQuery.SQL.Add(' SELECT * FROM TABLA WHERE (campo BETWEEN :BUSCA_INI AND :BUSCA_FIN) ');
      qQuery.SQL.Add(' AND (campo LIKE :LIMITESPACO) ');
      qQuery.SQL.Add('  OR (campo LIKE :ESCRITEDIT)  ');
      qQuery.SQL.Add('  ORDER BY CAMPO  ');
      qQuery.Parameters.ParamByName('BUSCA_INI').Value :=  FEditPesq.Text;
      qQuery.Parameters.ParamByName('BUSCA_FIN').Value :=  FEditPesq.Text + 'Z'; // Este Z significa um delimitador de caracteres
                                                                                   // para ser contado 1 char a mais depois do STR
      qQuery.Parameters.ParamByName('LIMITESPACO').Value := '%'+ str +'%';
      qQuery.Parameters.ParamByName('ESCRITEDIT').Value := '%'+ FEditPesq.Text + '%';
      qQuery.Open;
    end;
  end;
end;

procedure TContainerFilter.OnEditChange(sender: TObject);
begin
  if Assigned(FEditChange) then
    AccessInsensitive(FsQuery,FEditPesq,0);
end;

procedure TContainerFilter.OnEditExit(sender: TObject);
begin
  if Assigned(FEditExit) then
     FEditExit(Sender);
end;

procedure TContainerFilter.OnBitBtn(sender: TObject);
begin
  if Assigned(FBitBtnClick) then
  begin
    Tag := 1;
    AccessInsensitive(FsQuery,FEditPesq,1);
  end;   
end;

//Metodos SpeedButtons
procedure TContainerFilter.OnSpeedButtonClick(sender: TObject);
begin
  //Aqui quero achar um modo de tratar cfe o GroupIndex do speedbutton
 { if FSpeedButton.GroupIndex = 1 then
  begin}
    if Assigned(FButtonClick) then
       FilterLetras( FsQuery,
                  (Sender as TSpeedButton).Caption[1],
                  (Sender as TSpeedButton).Caption[2] );
 {    FSpeedButton.GroupIndex := 0;
  end else
  begin
    AccessInsensitive(FsQuery,FEditPesq,0);
    FSpeedButton.GroupIndex := 1;
  end;} end; procedure TContainerFilter.OnSpeedButtonExit(sender: Tobject); begin   if Assigned(FButtonExit) then      FButtonExit(Sender); end; procedure TContainerFilter.SetAutoSize(const Value: Boolean); begin   if FAutoSize <> Value then   begin     FAutoSize := Value;     if Value then       AdjustSize; //comando da classe Controls   end; end; procedure TContainerFilter.SetButtonAutoSize(const Value: Boolean); begin   if FButtonAutoSize <> Value then   begin     FButtonAutoSize := Value;     if Value then       AdjustSize; //comando da classe Controls   end; end; procedure TContainerFilter.RestrictSize(var msg: TMessage); begin   if (Assigned(FSpeedButton)) then   begin     FSpeedButton.Left  := cLeftSeedButton;     FSpeedButton.Width := (Self.Width div 3)-20;     Self.Font.Size := Trunc(15 * Self.Height/cHeigthPanelRigth);   end; end; end.




Responder

Gostei + 0

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar