首先創建一個新的項目,然後向窗體上添加一個TQuery組件和一個TListVIEw組件。添加組件後的窗體如圖1所示。
圖1 主界面
設置TQuery組件的DatabaseName屬性設置為DBDEMOS,SQL屬性設置為select * from country,Active屬性設置為True。然後添加程序初始化代碼如下:
procedure TForm1.FormCreate(Sender: TObject);
var
i:Integer;
TempColumn:TListColumn;
TempItem:TListItem;
begin
ListView1.VIEwStyle:=vsReport;
for i:=0 to Query1.FIEldCount-1 do
begin
TempColumn:=self.ListVIEw1.Columns.Add;
TempColumn.Caption:=Query1.Fields[i].FIEldName;
end;
Query1.First;
while not Query1.Eof do
begin
TempItem:=self.ListVIEw1.Items.Add;
TempItem.Caption:=Query1.FIElds[0].AsString;
for i:=1 to Query1.FIEldCount-1 do
begin
TempItem.SubItems.Add(Query1.FIElds[i].AsString);
end;
Query1.Next;
end;
end;
程序首先通過ListView1.ViewStyle:=vsReport語句設置TListView組件的ViewStyle屬性值為vsReport。然後通過第1個循環中的TempColumn:=self.ListView1.Columns.Add和TempColumn.Caption:=Query1.Fields[i].FieldName語句在TListVIEw組件的標題行中顯示數據庫中字段的名稱。最後通過一個循環逐行輸出數據庫的所有數據。
程序代碼如下:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ADODB, Grids, DBGrids, ComCtrls, DBTables;
type
TForm1 = class(TForm)
Query1: TQuery;
ListView1: TListVIEw;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
i:Integer;
TempColumn:TListColumn;
TempItem:TListItem;
begin
ListView1.VIEwStyle:=vsReport;
for i:=0 to Query1.FIEldCount-1 do
begin
TempColumn:=self.ListVIEw1.Columns.Add;
TempColumn.Caption:=Query1.Fields[i].FIEldName;
end;
Query1.First;
while not Query1.Eof do
begin
TempItem:=self.ListVIEw1.Items.Add;
TempItem.Caption:=Query1.FIElds[0].AsString;
for i:=1 to Query1.FIEldCount-1 do
begin
TempItem.SubItems.Add(Query1.FIElds[i].AsString);
end;
Query1.Next;
end;
end;
end.
保存文件,然後按F9鍵運行程序,程序運行結果如圖2所示。
圖2 程序運行結果