EDelphi XE8 "List index out of bounds (-1)" when clicking the empty line in ListBox

2.5k Views Asked by At

I've recently switched to Embracadero Delphi XE8 from good ol' Delphi 7, and now i'm constantly receiving this error. It appears every time i misclick an empty line in any ListBox - something i couldn't do in D7. Is this some kind of bug, or am i doing something wrong?

UPD: Here is an OnClick procedure for one of ListBox'es in question:

procedure TMainForm.ChoiceListBoxClick(Sender: TObject);
begin
Choice:=ChoiceListBox.Items[ChoiceListBox.ItemIndex];
ChoiceListBox.Items.Clear;
if InDialogueWith<>'' then DialoguesUnit.Dialogue
else ActionsUnit.Actions;
end;

It saves player's choice into a variable, clears the list and then relays it to a certain procedure, depending on the situation. As i've said before, everything worked just fine in DE7 - i just couldn't click on empty lines in ListBox.

1

There are 1 best solutions below

0
On BEST ANSWER

There is a fundamental flaw in the code you've posted, which is the failure to check the value of the ChoiceListBox.ItemIndex to ensure an item is selected before using it to access ChoiceListBox.Items.

When a TListBox is first created, there is no item selected by default (unless you say otherwise by setting the ItemIndex in the Object Inspector or in code. TListBox.OnClick is called whenever the listbox is clicked, whether the click is over an item or not. You need to ensure that an item has first been selected before attempting to use that item.

The proper code would be along the lines of

procedure TMainForm.ChoiceListBoxClick(Sender: TObject);
begin
  if ChoiceListBox.ItemIndex <> -1 then
  begin
    Choice:=ChoiceListBox.Items[ChoiceListBox.ItemIndex];
    ChoiceListBox.Items.Clear;
    if InDialogueWith <> '' then 
      DialoguesUnit.Dialogue
    else 
      ActionsUnit.Actions;
  end;
end;

Note that as you've not specified otherwise, and because you refer to Delphi 7 as the version you're upgrading from, I'm presuming your question refers to the VCL. As the last several versions of the IDE include both VCL and FMX controls that share the same names, it's usually better to include a tag (or some text) indicating which UI controls you're using.