Moussamoa
Moussamoa

Reputation: 427

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

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?

Upvotes: 8

Views: 17846

Answers (4)

LegitLearner
LegitLearner

Reputation: 89

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;

Upvotes: 0

Max Kleiner
Max Kleiner

Reputation: 1622

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

TListview(sender).items[TListview(sender).itemindex].subitems[1]);

Upvotes: 1

LU RD
LU RD

Reputation: 34939

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.

Upvotes: 13

Dalija Prasnikar
Dalija Prasnikar

Reputation: 28541

Use Index property of Selected item

if lvClients.Selected <> nil then
  index := lvClients.Selected.Index;

Upvotes: 5

Related Questions