2014-02-15 15 views
0

我哈瓦一个脚本错误:德尔福对于每个TListItem在ListView1的

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; 

的错误是:为tlistitem在listview1.items做,但我不知道什么是错的,有人可以帮助我?

+0

请不要在不包含错误的情况下询问有关错误的问题。 –

回答

6

TListItem是一种类型。您必须在循环中使用该类型的局部变量。

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

参见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.

如果你想删除一个项目,你必须通过一个有效的索引。

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

TServerWinSocket.Connections期待一个整数索引,这样看来,你必须将项目转换为指数如上显示。

如果您的目标是删除断开连接的对象,并且您通过测试所有项目来完成此操作,则应该使用正常的自上而下循环来代替循环。

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

您可以在'for..in..'循环中使用'TListItem.Index'属性。 –

+0

@Remy不适用于删除部分 –

1

这段代码有很多问题。首先,在循环需要一个本地循环变量:

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

纵观你的代码中使用其中需要变量

您的一揽子异常处理程序很差。它会吞噬所有的例外。将其更改为仅处理预期的异常。

这似乎不大可能,

ServerSocket1.Socket.Connections[Item] 

可以通过项目,你试图做索引。在代码的这一点你必须重新思考你的意思。

最后,作为一般规则,您不能在修改容器的同时迭代它。当您拨打Delete从列表中删除项目时,您可以这样做。我认为你需要建立一个项目清单,当你迭代列表。然后当迭代完成时,删除项目。并且请注意,Delete期望索引而不是项目作为其参数。

作为更普遍的建议,使用GUI控件作为主数据容器通常是一个坏主意。这个设计决定可能会回到困扰你的地方。