Mahm00d
Mahm00d

Reputation: 3921

Delphi: One procedure to change all the fields of a record?

I have a record like this:

Tcustomer=record
  Name: string;
  IDNumber: Integer;
  IsMarried: boolean;
end;

And I have a TCustomers_Manager class that stores a list of all the customers. Is it possible to have a procedure like this:

Procedure ChangeCustomer(CustomerIndex: integer; field: string; value);

That sets the value for that specific field. For example:

ChangeCustomer(1, 'Name','John');

How can I implement this?

Update: To clarify, my question is basically in 2 parts:

1) How can I map the field name (in string) to the actual field in record?

2) Is it possible to pass a value that has different types? Or should I pass a single type and type cast it (like passing a string and then using strtoint())

Upvotes: 0

Views: 1594

Answers (2)

Marco
Marco

Reputation: 57583

You could, for example, do this (assuming lst: TList<TCustomer> as you said in a comment):

Procedure ChangeCustomer(index: integer; i: byte; value: variant)
begin
    case (i) of
        0: lst[index].Name := value;
        1: lst[index].IDNumber := value;
        2: lst[index].IsMarried := value;
    end;
end;

You could use a type (or enum) in place of i: byte. I dont't use Delphi from long time, so take my example as an idea, not like a Delphi app!!

Upvotes: 1

George
George

Reputation: 84

I would use TClientDataSet.

  1. Create TClientDataSet with fields ID, Name, etc.
  2. Open Dataset, Fill with InsertRecord or Insert/Post
  3. Find Record with Locate
  4. Use FieldByName('FieldName').Value to access to or change data

Or you can take any MemoryDataSet component and use it in same way.

Second way is to convert record to class, declare Fields as published and use SetPropValue.

If you want to pass any Value you can use Variant. But you have to check types before assign.

Upvotes: 3

Related Questions