Author: Tomas Rutkauskas
How do I create a Collection myself? I need a Collection of Items with ArticelNr,
Name, Price, etc.. Each item should be in the collection of ResellItems.
Answer:
First, you need to create your ResellItem class based upon TCollectionItem:
1 TResellItem = class(TCollectionItem)
2 private3 fArticleNr: integer;
4 fName: string;
5 fPrice: double;
6 public7 property ArticleNr: integer read fArticleNr write fArticleNr;
8 property Name: stringread fName write fName;
9 property Price: double read fPrice write fPrice;
10 end;
The next step is optional although I generally find it useful (self-documents for a
start): create a descendent of TCollection:
11 TResellCollection = class(TCollection)
12 end;
13 14 15 //Now you need to declare an instance somewhere:16 17 18 var19 ResellCollection: TResellCollection;
20 21 22 //The constructor for TCollection takes a TCollectionItem class parameter:23 24 25 ResellCollection: TResellCollection.Create(TResellItem);
26 27 28 //Having created our collection (don't forget to free it afterwards) then adding 29 items becomes:
30 31 32 var33 item: TResellItem;
34 35 item := ResellCollection.Add as TResellItem;
36 item.ArticleNr := aNumber;
37 item.Name := aName;
38 item.Price := aPrice;
I generally wrap the above code into a TResellCollection method, say AddResellItem,
thus allowing:
ResellCollection.AddResellItem(aNumber, aName, aPrice);
Accessing items afterwards is done like this:
item := ResellCollection.Items[index] as TResellItem;
The syntax above can be simplified by adding a new default array property to
TResellCollection, thus encapsulating the messy casting:
property ResellItem[index: integer]: TResellItem read GetResellItem; default;
The GetResellItem method required looks like this:
39 function TResellCollection.GetResellItem(index: integer): TResellItem;
40 begin41 Result := Items[index] as TResellItem;
42 end;
43 44 45 //Now you can say things like:46 47 48 item := ResellCollection[0];
49 ResellCollection[1].Name := newname;
Just in case you have got a bit lost with the changes, the interface and
implementation of TResellCollection now look like this:
50 TResellCollection = class(TCollection)
51 private52 function GetResellItem(index: integer): TResellItem;
53 public54 procedure AddResellItem(aNumber: integer; const aName: string; aPrice: Double);
55 property ResellItem[index: integer]: TResellItem read GetResellItem;
56 default;
57 end;
58 59 procedure TResellCollection.AddResellItem(aNumber: integer; const aName: string;
60 aPrice: Double);
61 var62 item: TResellItem;
63 begin64 item := Add as TResellItem;
65 item.ArticleNr := aNumber;
66 item.Name := aName;
67 item.Price := aPrice;
68 end;
69 70 function TResellCollection.GetResellItem(index: integer): TResellItem;
71 begin72 Result := Items[index] as TResellItem;
73 end;