"List index out of bounds" on TListBox

Christopher Chase picture Christopher Chase · Sep 28, 2010 · Viewed 7.3k times · Source

I have a TListBox on a form, and items are added with

listbox1.ItemIndex := listbox1.Items.AddObject('msg', TObject(grp));

grp is an integer. The listbox is set to lbOwnerDrawFixed.

In the onDrawItem event I get the exception EStringListError raised on the marked line:

msg := (control as Tlistbox).Items.Strings[index];           // this line works
grp := integer((control as Tlistbox).Items.Objects[index]);  // exception here

msg and grp are local string and integer variables.

Project ### raised exception class EStringListError with message 'List index out of bounds (1)'

Answer

Christopher Chase picture Christopher Chase · Sep 28, 2010

Silly mistake: I was using grp := -1 as the default group, which AddObject or Objects[index] must not like.