14K
14K

Reputation: 85

Add icon to TListView

I'm trying to put an icon in TListView when certain rows show and I have the TImageList with the loaded image, but it does not connect. The code that I have is this

with sListView2 do
begin
  test := sListView2.Items.Add;
  test.Caption := sListbox2.Items[i];
  test.SubItems.Add(test');
  test.ImageIndex(ImageList1.AddIcon(1));
end;

Could someone tell me what I'm doing wrong ?

Upvotes: 2

Views: 5186

Answers (1)

Ken White
Ken White

Reputation: 125748

TImageList.ImageIndex is an integer, and you need to properly set it, and to call AddIcon you need to provide it a TIcon.

If you already have it in the TImageList, just set the TListView.ImageIndex to the proper index of that image:

// Assign an image from the ImageList by index
test.ImageIndex := 1;  // The second image in the ImageList

Or, if you don't have an existing icon in the TImageList and need to add one, add it and store the return value from AddIcon:

// Create a new TIcon, load an icon from a disk file, and
// add it to the ImageList, and set the TListView.ImageIndex
// to the new icon's index.
Ico := TIcon.Create;
try
  Ico.LoadFromFile(SomeIconFileName);
  test.ImageIndex := ImageList1.Add(Ico);
finally
  Ico.Free;
end;

BTW, you can simplify your code slightly (be careful with with, though!):

with sListView2.Items.Add do
begin
  Caption := sListbox2.Items[i];
  SubItems.Add(test');
  ImageIndex := 1;
end;

Upvotes: 3

Related Questions