2013-07-15 55 views
1

如何編寫DBGrid.SelectedRows.Count更改時觸發的自定義事件?如何編寫DBGrid.SelectedRows.Count更改時觸發的自定義事件?

我需要這個事件來有條件地顯示/隱藏一個面板,當DBGrid中的選定行是[零|一個]或不止一個。

因爲現在,我使用下面的代碼,但IMO編碼自定義事件是比較合適的位置:

TForm3.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; Field: TField; State: DBGridDrawState); 
begin 
    Panel1.Visible := TDBGrid(Sender).SelectedRows.Count > 1; 
end; 
+0

您應該使用選擇行時發生的事件,例如'onclick'。 – lurker

+0

我需要一個與鼠標或鍵盤一起工作的通用事件:OnClick只適用於鼠標 –

+0

好的。然後我會建議檢查組件的keydown或keypress事件。看起來@bummi已經在他的回答中包含了這個概念。 – lurker

回答

2

要捕獲所有改變內部Bookmarklist YOE事件將要重寫

  1. LinkActive
  2. 的KeyDown
  3. 的MouseDown

上面的例子就像中介層類一樣,可以改成一個新的組件。

unit Unit1; 

interface 

uses 
    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 
    Dialogs, StdCtrls, Grids, DBGrids, DB, ADODB; 

type 
    TDBGrid=Class(DBGrids.TDBGrid) 
    private 
    FOnSelectionChanged: TNotifyEvent; 
    procedure LinkActive(Value: Boolean); override; 
    procedure KeyDown(var Key: Word; Shift: TShiftState);override; 
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; 
     X, Y: Integer); override; 
    published 
    published 
    property OnSelectionChanged:TNotifyEvent read FOnSelectionChanged write FOnSelectionChanged; 
    End; 

    TForm1 = class(TForm) 
    ADODataSet1: TADODataSet; 
    DataSource1: TDataSource; 
    DBGrid1: TDBGrid; 
    Button1: TButton; 
    procedure MyOnSelectionChanged(Sender: TObject); 
    procedure FormCreate(Sender: TObject); 
    procedure Button1Click(Sender: TObject); 
    private 
    { Private-Deklarationen } 
    public 
    { Public-Deklarationen } 
    end; 

var 
    Form1: TForm1; 

implementation 
uses unit3; 
{$R *.dfm} 

procedure TForm1.Button1Click(Sender: TObject); 
begin 
    AdoDataset1.Active := Not AdoDataset1.Active; 
end; 

procedure TForm1.FormCreate(Sender: TObject); 
begin 
    DBGrid1.OnSelectionChanged := MyOnSelectionChanged; 
end; 

procedure TForm1.MyOnSelectionChanged(Sender: TObject); 
begin 
    Caption := IntToStr(TDBGrid(Sender).SelectedRows.Count); 

end; 

{ TDBGrid } 

procedure TDBGrid.KeyDown(var Key: Word; Shift: TShiftState); 

begin 
    inherited; 
    if Assigned(FOnSelectionChanged) then FOnSelectionChanged(self); 

end; 

procedure TDBGrid.LinkActive(Value: Boolean); 
begin 
    inherited; 
    if Assigned(FOnSelectionChanged) then FOnSelectionChanged(self); 

end; 

procedure TDBGrid.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); 
begin 
    inherited; 
    if Assigned(FOnSelectionChanged) then FOnSelectionChanged(self); 

end; 

end. 
+1

非常感謝你@bummi!這正是我期待的! –

相關問題