Search code examples
delphidelphi-7

Assigning the selected items in a TxpComboBox to a variable


I'm attempting to assign all the selected items in a TxpListBox to a TStringList.

My initial thought was to do something like

Function AssignListBoxToList(ComponentName : TxpListBox) : Boolean;
var
  slComponentValue : TStringList;
begin    
  slComponentValue := TStringList.Create;
  slComponentValue.Add(ComponentName.Items);
end;

But it throws the following exception Incompatible types: 'String' and 'TString'.

Is there a way to either create a TStringList of TStrings, or is it safe to use String instead of TString in my TxpListBox, and/or am I missing something.

TxpListBox is a TListBox with a modified look to fit in with the Windows XP design aesthetic.


Solution

  • It looks like TxpComboBox.Items might be a TStrings descendent (like the standard TComboBox.Items). If that's the case, something like this should work:

    slComponentValue := TStringList.Create;
    slComponentValue.Add(ComponentName.Items[ComponentName.ItemIndex]);
    

    Your function won't work as is, though, because it doesn't return slComponentValue.

    It's generally not a good idea (without a specific reason to do so) to return an object from a function, because it's not clear where the responsibility lies to free it. I prefer to make that more clear by having a procedure accept an already-created instance of an object instead:

    procedure AssignComboBoxToList(ComponentName : TxpComboBox; 
        ListToFill: TStrings) : Boolean;
    begin    
      Assert(Assigned(ListToFill));
      ListToFill.Add(ComponentName.Items[ComponentName.ItemIndex);
    end;
    

    You can then use it like this:

    slComponentValue := TStringList.Create;
    try
      AssignComboBoxToList(YourComboBox, slComponentValue);
      if slComponentValue.Count > 0 then
        // Do whatever with the slComponentValue list
    finally
      slComponentValue.Free;
    end;
    

    However, as you're only dealing with a single string, it might be easier to just use a single string; there's not really a TStringList neededhere:

    strResult := YourComboBox.Items[YourComboBox.ItemIndex];
    

    With that being said, TComboBox doesn't support multiple selections; TListBox does, but TComboBox displays a drop down list and allows selecting of a single item, making your question somewhat unclear.