数组字段(ftArray) 与 ADT 字段类似(设计过程一样), 定义数组字段时只需定义一个元素来说明元素类型. 本例同时测试 ObjectView 为 True 和 False 时的不同效果. 下面是在运行时实现的数组字段: //先在窗体上放置: DBGrid1、DataSource1、ClientDataSet1 并关联, 然后: procedure TForm1.FormCreate(Sender: TObject); begin // ClientDataSet1.ObjectView := True; { 先定义两个基本字段 } with ClientDataSet1.FieldDefs.AddFieldDef do begin Name := ''ID''; DataType := ftInteger; end; with ClientDataSet1.FieldDefs.AddFieldDef do begin Name := ''Group''; DataType := ftString; Size := 7; end; { 定义数组字段: 假如数组包括 4 个元素 } with ClientDataSet1.FieldDefs.AddFieldDef do begin Name := ''Member''; DataType := ftArray; Size := 4; ChildDefs.Add(''TempName'', ftString, 11); { 只需定义一个子元素来说明元素类型 } end; ClientDataSet1.CreateDataSet; { 添加记录 } ClientDataSet1.AppendRecord([1, ''一组'', VarArrayOf([''A1'',''A2'',''A3'',''A4''])]); { 下面的添加方式也可用于访问 } ClientDataSet1.Append; ClientDataSet1[''ID''] := 2; ClientDataSet1[''Group''] := ''二组''; TArrayField(ClientDataSet1.FieldByName(''Member''))[0] := ''B1''; TArrayField(ClientDataSet1.FieldByName(''Member''))[1] := ''B2''; TArrayField(ClientDataSet1.FieldByName(''Member'')).FieldValues[2] := ''B3''; TArrayField(ClientDataSet1.FieldByName(''Member'')).FieldValues[3] := ''B4''; ClientDataSet1.Post; ClientDataSet1.Append; ClientDataSet1[''ID''] := 3; ClientDataSet1[''Group''] := ''三组''; TArrayField(ClientDataSet1.FieldByName(''Member'')).Fields[0].AsString := ''B1''; TArrayField(ClientDataSet1.FieldByName(''Member'')).Fields[1].AsString := ''B2''; TArrayField(ClientDataSet1.FieldByName(''Member'')).Fields[2].Value := ''B3''; TArrayField(ClientDataSet1.FieldByName(''Member'')).Fields[3].Value := ''B4''; ClientDataSet1.Post; end; { 可以通过下面代码查看 ObjectView 为 True 和 False 时的不同 } procedure TForm1.Button1Click(Sender: TObject); begin ClientDataSet1.Close; ClientDataSet1.ObjectView := not ClientDataSet1.ObjectView; Text := Format(''ObjectView: %s'', [BoolToStr(ClientDataSet1.ObjectView, True)]); ClientDataSet1.Open; end; (责任编辑:admin)
|