In Delphi 7, I’m using a TCheckListBox. I want it to use a TStringList rather than a TStrings, so I can set Duplicates to dupIgnore, and Sorted to TRUE.
Can I just do this:
Form1 = class(TObject
CheckListBox1: TCheckListBox; // created by the IDE
end;
procedure TForm1.FormCreate
begin
CheckListBox1.Items.Free;
CheckListBox1.Items := TStringList.Create;
CheckListBox1.Items.Sorted := TRUE;
CheckListBox1.Items.Duplicates := dupIgnore;
end;
Is this safe? Any caveats or suggestions?
EDIT: Removed declaration for MyStringList and added .Items to the last two assignment lines.
EDIT 2: Trying to compile the above, it looks like I’d have to cast the two final lines like this:
TStringList(CheckListBox1.Items).Sorted := TRUE;
TStringList(CheckListBox1.Items).Duplicates := dupIgnore;
Although I might be able to get this to run, I’m asking the question because just getting it to run doesn’t mean it will always run or is safe.
You don’t control what class
TCheckListBoxuses to store its items. Assigning theItemsproperty a value only assigns its items to the internal storage.Also, you shouldn’t call
Items.Free;.TCheckListBoxdepends on its internal instance ofTListBoxStrings.To answer your edits in your question: Don’t hard-cast the
Itemsproperty toTStringList, either. The typecast is wrong (the instance exposed byItemsis not aTStringList) and will only cause problems.Edit, to suggest a workaround for what you seem to try to achieve: To keep the checklistbox sorted, you can set its
Sortedproperty toTrue. To avoid duplicates, you can check the list before adding an item in code.