本实例演示如何在TListView组件中显示数据库的内容。
首先创建一个新的项目,然后向窗体上添加一个TQuery组件和一个TListView组件。添加组件后的窗体如图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所示。
原文:https://www.cnblogs.com/jijm123/p/14388452.html