在ClientDataSet中静态添加字段很容易,但是要在ClientDataSet已经获得数据打开了数据集的情况下添加就麻烦了。下图为在已经取得数据的情况下动态添加字图,请看最后列:

***************************************************************************************************************************

具体操作:

***************************************************************************************************************************

DBGrid1.DataSource->DataSource1.DataSet->ClientDataSet1.ProviderName->DataSetProvider1.DataSet->

SQLDataset1.SQLConnection->SQLConnection1具体数据库(这里连接的是oracle中的PERSONS表);

SQLDataSet1.CommandText:=SELECT * FROM PERSONS;ClientDataSet1.Active:=true;

***************************************************************************************************************************

主要代码:

***************************************************************************************************************************

procedure TForm3.Button1Click(Sender: TObject);
var
  I: integer;
  Field: TField;
begin
  ClientDataSet1.Close;
  SQLDataSet1.Active := true;
  ClientDataSet1.Fields.Clear;
  for I := 0 to SQLDataSet1.FieldCount - 1 do
  begin
    Field := SQLDataSet1.Fields.Fields[I];
    if Field.DataType = ftWideString then
    begin
      with TWideStringField.Create(self) do
      begin
        Name := Field.Name;
        FieldName := Field.FieldName;
        FieldKind := Field.FieldKind;
        DataSet := ClientDataSet1;
      end;
    end
    else if Field.DataType = ftFMTBcd then
    begin
      with TFMTBcdField.Create(self) do
      begin
        Name := Field.Name;
        FieldName := Field.FieldName;
        FieldKind := Field.FieldKind;
        DataSet := ClientDataSet1;
      end;
    end;
  end;
  // 添加计算字段
  with TIntegerField.Create(self) do
  begin
    Name := format('add%d',[Random(1000)]);
    FieldName := format('add%d',[Random(1000)]);
    FieldKind := fkCalculated;
    DataSet := ClientDataSet1;
  end;
  ClientDataSet1.FieldDefs.Update;
  ClientDataSet1.Open;

end;

以上代码在DELPHI XE5 ,WIN7 X64, ORACLE 11G环境下测试通过。

posted on 2017-03-06 21:43  sun繁星点点  阅读(750)  评论(0编辑  收藏  举报