Question

Right now I am using the following code to get a ListView items value and I was wanting to know if this was the proper way to do this or should I be doing it another way.

Example for the parent item value:

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(ListView1.Selected.Caption);
end;

Example for a sub item value:

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(ListView1.Selected.SubItems.Strings[items_index_here]);
end;
Was it helpful?

Solution

Your first code seems fine, except you should be checking to see if there is a Selected item first:

if Assigned(ListView1.Selected) then  // or ListView1.Selected <> nil
  ShowMessage(ListView1.Selected.Caption);

Your second can be simplified (and should include the same check I mentioned above):

if Assigned(ListView1.Selected) then
  ShowMessage(ListView1.Selected.SubItems[Index]);

TStrings descendants (like TStringList and TListItem.SubItems) have default properties, which is a shortcut to using TStrings.Strings[Index]; you can instead just use TStrings[Index]. Instead of MyStringList.Strings[0], you can just use MyStringList[0], and this applies to things like TMemo.Lines and TListItem.SubItems as well. You don't need SubItems.Strings[Index], but can just use SubItems[Index].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top