我正在WinXP下使用Delphi XE3。
使用以下代码:
procedure TForm1.Button1Click(Sender: TObject);
var
FileName: string;
begin
FFileList := TStringList.Create;
for FileName in TDirectory.GetFiles(Edit1.Text) do
FFileList.AddObject(FileName, nil);
ListView1.Items.Count := FFileList.Count;
end;
procedure TForm1.ListView1CustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
var
I: Integer;
begin
I := 0;
end;
procedure TForm1.ListView1Data(Sender: TObject; Item: TListItem);
begin
// The following error will never occur
if Item.Index >= ListView1.Items.Count then
Application.MessageBox('Invalid item index', 'Error');
Item.Caption := 'TestCaption';
end;
我将ListView1.OwnerData设置为True,将ListView1.OwnerDraw设置为False。
在XP下运行代码时,在TForm1.ListView1Data中,该应用程序将弹出“无效项索引”错误。为什么?
更新:
我已将整个项目源代码上传到https://www.dropbox.com/s/bsi7bh6xfkp6av3/Test4_1.zip?dl=0,这可以显示XP下的错误。
此link说,在加载WinXP主题时也会出现类似的错误。
似乎是越野车库错误地计算了位置索引对应关系。
解决方法-仅检查索引有效性
if (Item.Index > -1) and (Item.Index < ListView1.Items.Count) then
begin
...
end