问题
i currently use list view inside my project i wanted to get index of some item by finding its subitem string , i have listview with item and subitem , item caption := name
and subitem := id
i want to find the index of this item where sub item := id
, how could i do that , i searched while for some equations and didn't got one yet . reason that i need this because the subitem id have unique id and this much secure instead of using find item by caption
回答1:
You need to loop through the list view's Items
, looking at the proper subitem that you want to match. For instance, given a TListView
with three columns (A, B, and C), to search through column B to find something:
function TForm1.FindListIndex(const TextToMatch: string): Integer;
var
i: Integer;
begin
for i := 0 to ListView1.Items.Count - 1 do
if ListView1.Items[i].SubItems[1] = TextToMatch then
Exit(i);
Result := -1;
end;
Of course, substitute your own matching function (SameText, for instance):
if SameText(ListView1.Items[i].SubItems[1], TextToMatch) then
...;
If you want to search for a match in any sub-item, you just need a nested loop:
function TForm1.FindListIndex(const TextToMatch: string): Integer;
var
i, j: Integer;
begin
for i := 0 to ListView1.Items.Count - 1 do
for j := 0 to ListView1.Items[i].SubItems.Count - 1 do
if ListView1.Items[i].SubItems[j] = TextToMatch then
Exit(i);
Result := -1;
end;
来源:https://stackoverflow.com/questions/30249448/how-do-i-get-index-of-listview-item-where-its-subitem-equal-some-string-without