Question

I hava a script with an error:

procedure TForm1.ServerSocket1ClientDisconnect(Sender: TObject;
  Socket: TCustomWinSocket);
begin
for tlistitem in listview1.items do
    Try
        ServerSocket1.Socket.Connections[tlistitem].Sendtext('TestConnection');
      except
           listview1.Items.Delete(tlistitem);
    end;
end;

The error is in: for tlistitem in listview1.items do but i don't know what is wrong, can someone help me?

Was it helpful?

Solution

TListItem is a type. You must use a local variable of that type in the loop.

var
  item: TListItem;
begin
  for item in listView1.Items do
  ...

See Iteration Over Containers Using For statements.

The type of the iteration variable Element must match the type held in the container. With each iteration of the loop, the iteration variable holds the current collection member. As with regular for-loops, the iteration variable must be declared within the same block as the for statement.

Warning: The iteration variable cannot be modified within the loop. This includes assignment and passing the variable to a var parameter of a procedure. Doing so results in a compile-time warning.

If you want to delete an item, you must pass a valid index.

listView1.Items.Delete(listView1.Items.IndexOf(item));

The TServerWinSocket.Connections expects an integer index, so it seems as you have to convert the item to an index as showed above.

If your goal is to delete the disconnected object, and you do that by testing all items, you should iterate with a normal top down for loop instead.

for i := Pred(listView1.Items.Count) downto 0 do

OTHER TIPS

There are numerous problems with this code. Firstly, a for in loop requires a local loop variable:

var
  Item: TListItem;
....
for Item in listView1.Items do
  ....

Throughout your code you use a type where a variable is needed.

Your blanket exception handler is poor. It will swallow all exceptions. Change it to handle only expected exceptions.

It seems unlikely that

ServerSocket1.Socket.Connections[Item]

can be indexed by item as you attempt to do. You'll have to re-think what you mean at this point of the code.

Finally, as a general rule, you cannot modify a container whilst iterating over it. You do that when you call Delete to remove an item from the list. I think you need to build a list of items to remove as you iterate over the list. And then when the iteration is done, delete the items. And do note that Delete expects an index rather than an item as its parameter.

As a more general piece of advice, it's usually a bad idea to use a GUI control as your primary data container. Somewhere down the line this design decision is likely to come back to haunt you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top