Question

I'm trying to write a component that inherits from TClientDataset. On the create of the component in design time I want to instantiate a list of common fields that are used within my framework. The code below will execute without errors and the field will appear at run time but not design time. Can anyone help me? I'm sure its something trivial!

{ InheritedClientDataset }

constructor InheritedClientDataset.Create(AOwner: TComponent);
var
  Field : TField;
begin
  inherited;

  Field := TField.Create(self);
  Field.Name := 'ATestField';
  Field.FieldName := 'Test';
  Field.SetFieldType(ftInteger);
  //Field.DataType := ftInteger;
  Field.Size := 0;
  Field.FieldKind := fkData;

  self.Fields.Add(Field);
end;
Was it helpful?

Solution

Try creating your field using its fieldtype. For example, TIntegerField.

  MyField := TIntegerField.Create(Self);
  MyField.FieldName := 'MyFieldName';
  MyField.DataSet := Self;
  MyField.Name := Self.Name + '_' + MyField.FieldName;

That should work.

It will be available to controls but not the Fields Editor.

OTHER TIPS

Totally untested, but you should probably be adding to FieldDefs instead:

with FieldDefs.AddFieldDef do
begin
  DataType := ftInteger;
  Name := 'Field1';
end;

with FieldDefs.AddFieldDef do
begin
  DataType := ftString;
  Size := 25;
  Name := 'Field2';
end;

You may also have to add a call to CreateDataSet after the FieldDefs are added:

// After above code...
inherited CreateDataSet;

I have a feeling that in cases like this, you might be going against the design intention of the VCL component designtime. Fields are typically defined by someone who places a table object onto a data module, then set the dataset properties to a particular SQL or other table and selects the fields from that table, rather than a component with a fixed set of fields, which might be something problematic for the current architecture to support, even though you have a fix, are you sure there aren't problems with that approach?

Have you thought about an alternative approach? (Write a component with a public property that allows it to be connected to a dataset or datasource and put all your framework logic in that component). Leave the dataset class alone.

Do you really NEED to do an "IS A" relationship in OOP terms, or would your code actually be cleaner if you considered "HAS A link to a dataset" instead?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top