1

我在表单上有一个 TListBox,并添加了项目

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

grp是一个整数。列表框设置为lbOwnerDrawFixed

如果我在标记线上onDrawItem遇到异常:EStringListError

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

msg并且grp是本地字符串和整数变量。

项目 ### 引发异常类 EStringListError 并带有消息“列表索引超出范围 (1)”

4

2 回答 2

1

愚蠢的错误:我使用grp := -1的是默认组,AddObject或者Objects[index]必须不喜欢。

于 2010-09-28T01:08:56.193 回答
0

您只想存储一个整数,因此您应该将代码更改为

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

无需在此处存储对象,这使整个事情变得更容易和更具可读性。

您现在得到的例外是因为您无法使用索引检索对象,但必须使用与它们关联的字符串(的第一个参数AddObject)。正确的方法是这样的:

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

另请参阅本教程关于AddObject.

于 2010-09-28T00:51:55.307 回答