Search code examples
delphidelphi-xedelphi-xe7

Add set of items to checklistbox and read values after


Is there any way to fill and get a set of items from a checklistbox?

What I did:

  TColorItem = (ms_red, ms_blue, ms_green, ms_yellow);
  TColorItems = set of TColorItem;

I have a component and I can choose from the TColorItems

 TProperty = class(TCollectionItem)
 private
   FModuleItem: TColorItems;  
   procedure SetColorItem(const Value: TColorItems);    
 published
   property ColorTypes: TColorItems read FColorItem write SetColorItem;

 procedure SetColorItem(const Value: TColorItems);
 begin
   FColorItem := Value;
 end;

After I setted up (checked) the items in the component, I created a form.

My form looks like this:

enter image description here

If I check any of the items from the checklistbox I want to get the Result as a TColorItems set:

  • If Red and Green are checked the set must be

    Result := [ms_red, ms_green]

  • If Blue, Green and Yellow are checked:

    Result := [ms_blue, ms_green, ms_yellow] etc..

The Result must be in this [value1, value2] form; I want to work with it after.


Solution

  • Declare an array of strings which pairs with the TColorItem type.

    const
      ColorItemNames: array [TColorItem] of string = ('Red', 'Blue', 'Green', 'Yellow');
    

    Fill the TCheckListBox object with the array.

    var
      ci: TColorItem;
    begin
      for ci := Low(ColorItemNames) to High(ColorItemNames) do
        CheckListBox1.Items.AddObject(ColorItemNames[ci], TObject(ci));
    end;
    

    Get the values as a TColorItems from the Objects of the TCheckListBox.Items property.

    var
      i: Integer;
    begin
      Result := [];
      for i := 0 to CheckListBox1.Count-1 do begin
        if CheckListBox1.Checked[i] then
          Include(Result, TColorItem(CheckListBox1.Items.Objects[i]));
      end;
    end;