本例效果图:
代码文件:
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, DB, DBClient, StdCtrls, ExtCtrls; type TForm1 = class(TForm) Panel1: TPanel; Button1: TButton; Button2: TButton; ClientDataSet1: TClientDataSet; DataSource1: TDataSource; DBGrid1: TDBGrid; procedure FormCreate(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} {本来可以不写代码, 设置四个属性即可} procedure TForm1.FormCreate(Sender: TObject); var DataFile: string; begin {获取 CodeGear 共享安装的数据文件: country.xml 的路径} DataFile := GetEnvironmentVariable('COMMONPROGRAMFILES'); {C:\Program Files\Common Files} DataFile := DataFile + '\CodeGear Shared\Data\country.xml'; {country.cds 也可} DBGrid1.DataSource := DataSource1; {DBGrid 需要连接数据源} DataSource1.DataSet := ClientDataSet1; {数据源 DataSource 需要连接数据集} ClientDataSet1.FileName := DataFile; {让数据集 ClientDataSet 关联一个数据文件} {打开数据集} ClientDataSet1.Active := True; //或 ClientDataSet1.Open; end; end.
窗体文件:
object Form1: TForm1 Left = 0 Top = 0 Caption = 'Form1' ClientHeight = 251 ClientWidth = 439 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object Panel1: TPanel Left = 0 Top = 0 Width = 439 Height = 41 Align = alTop Caption = 'Panel1' TabOrder = 0 object Button1: TButton Left = 20 Top = 8 Width = 75 Height = 25 Caption = 'Button1' TabOrder = 0 end object Button2: TButton Left = 101 Top = 8 Width = 75 Height = 25 Caption = 'Button2' TabOrder = 1 end end object DBGrid1: TDBGrid Left = 0 Top = 41 Width = 439 Height = 210 Align = alClient TabOrder = 1 TitleFont.Charset = DEFAULT_CHARSET TitleFont.Color = clWindowText TitleFont.Height = -11 TitleFont.Name = 'Tahoma' TitleFont.Style = [] end object DataSource1: TDataSource Left = 160 Top = 104 end object ClientDataSet1: TClientDataSet Aggregates = <> Params = <> Left = 168 Top = 112 end end