Search code examples
delphilistboxindexoutofboundsexceptionlazaruststringlist

Delphi, Lazarus - Listbox out of bound (0) TString


I simply can't seem to make any sense of the following error.

Listbox out of bound (0) TString

I have a form or window with a listbox and following code is supposed to work with it. It suppose to get a list of strings from an ini file and set to the listbox.

IF selectedbox1count <> 0 then
BEGIN
   FOR i:=0 to selectedbox1count-1 do
      selectedbox.items[i] := AInifile.ReadString('DATAVIEW2', 'SHIFT1CHART'+(i+1), ' ');
END;

But it always pops up a error message at the first instance it reaches the selectedbox.items[i] line. Read of ini file returns "NEW CHART 2" string. Am I missing something here?

UPDATE: selectedbox1count holds value from the ini file ...


Solution

  • The error is telling you that the list box selectedbox is empty. I would expect that the error is more like this:

    List index out of bounds (0)

    That tells you that index 0 is invalid which can only mean that there are no items in the list box.

    Presumably selectedbox1count is not in fact the number of items in the list box. Get that with selectedbox.Count or selectedbox.Items.Count.

    You can only modify items that already exist. So clearly you need to add items to the rest. Do so by calling selectedbox.AddItem or selectedbox.Items.Add.

    for i := 0 to selectedbox1count - 1 do
      selectedbox.AddItem(...);