siddharth taunk
siddharth taunk

Reputation: 319

Not able to Iterate through TListView

Why is the following code not iterating through the ListView?

  for x := 1 to ListView1.Items.Count do
  Begin
    PName := ListView1.Items.Item[i].Caption;
    Variable := ListView1.Items.Item[i].SubItems[0];
    Val := ListView1.Items.Item[i].SubItems[1];
    ToFIle(PName, Variable, Val);
  End;

Upvotes: 0

Views: 917

Answers (2)

David Heffernan
David Heffernan

Reputation: 612794

  • Your loop variable is x, but you use i inside the loop body.
  • You iterate over the wrong indices. Indices in Delphi are, by convention, zero-based. Your loop should run from 0 to Count-1.

Some other points:

  • x is not a great variable name for an integer index. Use i or index.
  • The Item property of TListItems is the default property so your code can be simplified by omitting that property.

I would write the code should like so:

var
  i: Integer;
  PName, Variable, Val: string;
....
for i := 0 to ListView1.Items.Count-1 do
begin
  PName := ListView1.Items[i].Caption;
  Variable := ListView1.Items[i].SubItems[0];
  Val := ListView1.Items[i].SubItems[1];
  ToFIle(PName, Variable, Val);
end;

Or by taking a reference to each item and thus avoiding repetition:

var
  i: Integer;
  Item: TListItem;
  PName, Variable, Val: string;
...
for i := 0 to ListView1.Items.Count-1 do
begin
  Item := ListView1.Items[i];
  PName := Item.Caption;
  Variable := Item.SubItems[0];
  Val := Item.SubItems[1];
  ToFIle(PName, Variable, Val);
end;

Or by using a for/in loop and not needing to care about indexing of the list items:

var
  Item: TListItem;
  PName, Variable, Val: string;
...
for Item in ListView1.Items do
begin
  PName := Item.Caption;
  Variable := Item.SubItems[0];
  Val := Item.SubItems[1];
  ToFIle(PName, Variable, Val);
end;

Upvotes: 7

Roman Marusyk
Roman Marusyk

Reputation: 24569

How is can iterating if you use as loop variable x but inside loop i.

And this one:

for x := 1 to ListView1.Items.Count do

is not correct because you never reach the first element. Please change to:

for x := 0 to ListView1.Items.Count - 1 do
  Begin
    PName := ListView1.Items.Item[x].Caption;
    Variable := ListView1.Items.Item[x].SubItems[0];
    Val := ListView1.Items.Item[x].SubItems[1];
    ToFIle(PName, Variable, Val);
  End;

Upvotes: 1

Related Questions