Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TStrings vs TStringList in TCheckListBox

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.

like image 237
RobertFrank Avatar asked Oct 18 '25 18:10

RobertFrank


1 Answers

You don't control what class TCheckListBox uses to store its items. Assigning the Items property a value only assigns its items to the internal storage.

Also, you shouldn't call Items.Free;. TCheckListBox depends on its internal instance of TListBoxStrings.

To answer your edits in your question: Don't hard-cast the Items property to TStringList, either. The typecast is wrong (the instance exposed by Items is not a TStringList) 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 Sorted property to True. To avoid duplicates, you can check the list before adding an item in code.

like image 67
Ondrej Kelle Avatar answered Oct 20 '25 15:10

Ondrej Kelle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!