How to get current index of selected item in Delphi TListView?
Asked Answered
A

4

8

I have a TListView in a form and I would like to know the index of the selected item. I tried to find a method or a property of my TListView which gives that information but the only thing I found was lvClients.Selected and it doesn't give the index of this item.

How to get the index of the selected item in my TListView?

Arlina answered 24/3, 2015 at 8:57 Comment(0)
C
13

Use the ItemIndex property.

A value of -1 indicates no selection.

From documentation:

Read ItemIndex to determine which item is selected. The first item in the list has index 0, the second item has index 1, and so on. If no item is selected, the value of ItemIndex is -1. If the list control supports multiple selected items, ItemIndex is the index of the selected item that has focus.

Cowfish answered 24/3, 2015 at 9:4 Comment(4)
Thanks, I wonder why it doesn't appear in the code autocompletion when I type it...Arlina
You're welcome. It does show up in autocompletion in XE7 at least.Cowfish
It should appear in code autocompletion just fine. It does so in every Delphi version I know and I started back in Delphi 6. The only reason why this couldn't work is if you are hitting bug that was present in some Delphi versions where code insight didn't work properly on really big projects or if you have some syntactical error in the code somewhere above your current code position as this can prevent code insight to properly scan whole unit.Distill
I'm on Delphi 6 and the project I am working on is really big (several million lines of code). Maybe that's the reason why it doesn't work properly. Thanks for the extra info.Arlina
L
5

Use Index property of Selected item

if lvClients.Selected <> nil then
  index := lvClients.Selected.Index;
Ludhiana answered 24/3, 2015 at 9:3 Comment(2)
Which is exactly how the TListView.ItemIndex property getter is implemented internally.Hyetography
this 2nd line gave me AV !!Kaneshakang
P
1

On a click event() you can also reach the column with subitems:

TListview(sender).items[TListview(sender).itemindex].subitems[1]);
Phosphorus answered 23/10, 2020 at 12:16 Comment(0)
H
0

you must cast it as such: TListViewItem(ListView1.Selected).Index for example:

procedure TfrmMain.ListView1ItemClick(const Sender: TObject;
  const AItem: TListViewItem);
begin

  { Old usage was like this:
    // Label1.Text := ListView1.Selected.Text;
  }
  // Now we have to cast it as such:

  Label1.Text := TListViewItem(ListView1.Selected).Index;
    
  // New usage of TListViewItem's selected item properties
  {
    TListViewItem(ListView1.Selected).ButtonText;
    TListViewItem(ListView1.Selected).Text;
    TListViewItem(ListView1.Selected).Index;
    TListViewItem(ListView1.Selected).Detail;
   ...
  }
end;
Haggerty answered 24/8, 2022 at 8:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.