本文整理自网络,侵删。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ActnList, ComCtrls, DB, ADODB, StdCtrls;
type
TForm1 = class(TForm)
ListView1: TListView;
ADOQuery1: TADOQuery;
Button1: TButton;
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;
//这个和Object Inspector 中的Columns对应,只不过这里是一列
//而那个是列的集合
TempColumn:TListColumn;
//这个和Object Inspector 中的Items对应,只不过这里是一行
//而那个是行的集合
TempItem:TListItem;
begin
try
ListView1.ViewStyle:=vsReport;
ADOQuery1 := TADOQuery.Create(nil);
ADOQuery1.Close;
ADOQuery1.ConnectionString := 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=test;Data Source=.';
ADOQuery1.SQL.Add('select * from userinfo');
ADOQuery1.Open;
//判断数据库中是否有记录
if not ADOQuery1.IsEmpty then
begin
//记录集中字段的个数
for I:=0 to ADOQuery1.FieldCount-1 do
begin
//增加一列
TempColumn:=self.ListView1.Columns.Add;
TempColumn.AutoSize := true;
//列的名字按照字段名命名
TempColumn.Caption:=ADOQuery1.Fields[I].FieldName;
end;
ADOQuery1.First;
//判断记录是否到最后
while not ADOQuery1.Eof do
begin
//增加一行
TempItem:=self.ListView1.Items.Add;
//行的名字是数据库中第一个字段的值
TempItem.Caption:=ADOQuery1.Fields[0].AsString;
for I:=1 to ADOQuery1.FieldCount-1 do
begin
//这里的SubItems和上面的Caption位于同一行
TempItem.SubItems.Add(ADOQuery1.Fields[I].AsString);
end;
ADOQuery1.Next;
end;
end;
finally
ADOQuery1.Free;
end;
end;
end.
相关阅读 >>
更多相关阅读请进入《Delphi》频道 >>