Delphi中用TListView显示数据库数据
本实例演示如何在TListView组件中显示数据库的内容。
首先创建一个新的项目,然后向窗体上添加一个TQuery组件和一个TListView组件。添加组件后的窗体如图1所示。
<喎?http://www.zzzyk.com/kf/ware/vc/" target="_blank" class="keylink">vc3Bhbj48YnIvPg0KICAgICAgICAgICAgzbwxINb3vefD5jwvZGl2Pg0KICAgICAgICAgICAgPC90ZD4NCiAgICAgICAgPC90cj4NCiAgICA8L3Rib2R5Pg0KPC90YWJsZT4NCjxici8+DQrJ6NbDVFF1ZXJ51+m8/rXERGF0YWJhc2VOYW1lyvTQ1Mno1sPOqkRCREVNT1OjrFNRTMr00NTJ6NbDzqpzZWxlY3QgKiBmcm9tIGNvdW50cnmjrEFjdGl2Zcr00NTJ6NbDzqpUcnVloaPIu7rzzO2807PM0PKz9cq8u6+0+sLryOfPwqO6PGJyLz4NCjxici8+DQo8dGFibGUgYm9yZGVyY29sb3I9"#cccccc" width="90%" align="center" bgcolor="#e3e3e3" border="1">
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; inte易做图ce 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 程序运行结果 |
补充:软件开发 , Delphi ,