删除OnDraw中的列表框项?

时间:2012-10-19 22:18:49

标签: delphi delphi-7

我有一个列表框并向其添加项目,项目是文件的地址,项目是在一些进程之后添加的,它们是这样插入的:

Listbox_Browser.Items := myItems;

因此我不能逐个添加它们,我在插入ti列表框时无法检查它们,我试图在OnDraw中检查它们并使用这样的代码:

  Try
    FileOpenandP(Listbox_Browser.Items[Index]);
  Except
    ListBox_Browser.Items.Delete(Index);
  End;

但我收到错误“List index out of bounds”,解决方案是什么?

1 个答案:

答案 0 :(得分:7)

OnDrawItem事件适用于仅绘图。您不应该在该事件中管理您的列表,只需根据需要绘制其当前项目。

不是一次分配整个列表,而是应该首先检查文件,然后将剩余的列表分配给ListBox,例如:

I := 0;
while I < myItems.Count do
begin
  try
    FileOpenandP(myItems[I]);
    Inc(I);
  except
    myItems.Delete(I);
  end;
end;
ListBox_Browser.Items := myItems;

如果您不想更改myItems,请改为使用单独的列表:

tmpItems := TStringList.Create;
try
  tmpItems.Assign(myItems);
  I := 0;
  while I < tmpItems.Count do
  begin
    try
      FileOpenandP(tmpItems[I]);
      Inc(I);
    except
      tmpItems.Delete(I);
    end;
  end;
  ListBox_Browser.Items := tmpItems;
finally
  tmpItems.Free;
end;

或者:

ListBox_Browser.Items := myItems;
I := 0;
while I < ListBox_Browser.Items.Count do
begin
  try
    FileOpenandP(ListBox_Browser.Items[I]);
    Inc(I);
  except
    ListBox_Browser.Items.Delete(I);
  end;
end;

或者:

ListBox_Browser.Items.BeginUpdate;
try
  ListBox_Browser.Items.Clear;
  I := 0;
  for I := 0 to myItems.Count-1 do
  begin
    try
      FileOpenandP(myItems[I]);
    except
      Continue;
    end;
    ListBox_Browser.Items.Add(myItems[I]);
  end;
finally
  ListBox_Browser.Items.EndUpdate;
end;