本例效果圖:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, DB, DBClIEnt, StdCtrls, ComCtrls, ExtCtrls;
type
TForm1 = class(TForm)
DataSource1: TDataSource;
ClientDataSet1: TClIEntDataSet;
DBGrid1: TDBGrid;
TreeView1: TTreeVIEw;
Splitter1: TSplitter;
procedure FormCreate(Sender: TObject);
procedure TreeVIEw1Change(Sender: TObject; Node: TTreeNode);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
node: TTreeNode;
List: TStringList;
s: string;
begin
{country.xml 是 Delphi 的數據示范文件, 也可以用 country.cds}
ClIEntDataSet1.FileName := 'c:\temp\country.XML';
ClIEntDataSet1.Active := True;
DataSource1.DataSet := ClIEntDataSet1;
DBGrid1.DataSource := DataSource1;
{上面四行是讓數據構件互相掛接, 也可以在設計時設定}
{建立 List}
List := TStringList.Create;
List.Sorted := True; {指定排序}
List.Duplicates := dupIgnore; {避免重復}
{把數據加入到 TreeVIEw}
for i := 0 to ClientDataSet1.FIEldDefs.Count - 1 do
begin
node := TreeView1.Items.Add(nil, ClientDataSet1.FIEldDefs[i].Name); {字段名}
{為避免數據重復, 先把數據給 List}
List.Clear;
ClIEntDataSet1.First;
while not ClIEntDataSet1.Eof do
begin
List.Add(ClientDataSet1.FIElds[i].value);
ClIEntDataSet1.Next;
end;
{把 List 中的數據加入到 TreeVIEw}
for s in List do TreeVIEw1.Items.AddChild(node, s);
end;
List.Free;
end;
procedure TForm1.TreeVIEw1Change(Sender: TObject; Node: TTreeNode);
begin
if Node.Parent <> nil then
begin
{下面的 Filter 其實就是 SQL 查詢語句, 如果用其他數據庫替換就是}
ClIEntDataSet1.Filter := Node.Parent.Text + '=''' + Node.Text + '''';
ClIEntDataSet1.Filtered := True;
end else ClIEntDataSet1.Filtered := False; {選字段名時取消過慮}
end;
end.
附數據庫樣本: