“List index out of bounds” on TListBox

眉间皱痕 提交于 2019-12-13 00:38:03

问题


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)'


回答1:


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




回答2:


You just want to store an integer, so you should change your code to

listbox1.ItemIndex := listbox1.Items.Add(IntToStr(grp));
[...]
grp := StrToInt((control as TListBox).Items[index]);

No need for storing objects here and this makes the whole thing much easier and more readable.

The exception you get now is because you can't retrieve objects using the index, but have to use the string you associated them with (the first parameter of AddObject). The correct way would be something like this:

msg := (control as Tlistbox).Items.Strings[index];
grp := integer((control as Tlistbox).Items.Objects[(control as Tlistbox).Items.IndexOf(msg)]);

Also see this tutorial about AddObject.



来源:https://stackoverflow.com/questions/3808921/list-index-out-of-bounds-on-tlistbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!