Lazarus 无法获取组合框所选项目值

Lazarus 无法获取组合框所选项目值,lazarus,Lazarus,我现在正在使用这个代码。我需要获取组合框中选定项的字符串值: procedure TForm5.BitBtn5Click(Sender: TObject); var c,k,t,g: string; begin //Get the name of the items c := ComboBox1.Items[ComboBox1.ItemIndex]; k := ComboBox2.Items[ComboBox2.ItemIndex]; t := ComboBox3.Items[Comb

我现在正在使用这个代码。我需要获取组合框中选定项的字符串值:

procedure TForm5.BitBtn5Click(Sender: TObject);
var c,k,t,g: string;
begin

 //Get the name of the items
 c := ComboBox1.Items[ComboBox1.ItemIndex];
 k := ComboBox2.Items[ComboBox2.ItemIndex];
 t := ComboBox3.Items[ComboBox3.ItemIndex];
 g := ComboBox4.Items[ComboBox4.ItemIndex];

 //Show it
 ShowMessage(c);

 end;
正如您所看到的,组合框中有项目,因为我在表单5的
onCreate
事件中填充了它们。按下BitBtn5时,出现如下错误:


我用谷歌搜索了我的问题,我发现代码是一样的,但我有那个错误。你知道吗?(我使用的是lazarus 1.2.4)

组合框的项目索引中至少有一个是-1。在form Creation中将它们设置为有效索引,例如:

ComboBox1.ItemIndex := 0;

我用的是Lazarus 1.4.2。问题在于,从组合框中选择项目时,属性ItemIndex没有更新。 为了强制更新此索引,我只在ComboBox的OnChange事件中放置了一些伪代码(即访问ItemIndex)(见下文)。然后我可以从其他地方读取ItemIndex,并且该值是正确的

procedure TForm1.ComboBoxChange(Sender: TObject);
var
  i: integer;
begin
  i := ComboBox.ItemIndex;
end;

我现在遇到了这个问题,在互联网上没有找到合适的解决方案。我的帖子已经很晚了,但我希望这会对其他人有所帮助。

通过
ComboBox.Text
@TLama获得这些值更安全(如果这是你的目标的话)。我没有想到这一点,它太简单了。。。很有效,谢谢。但我仍然不知道为什么我的代码是错误的删除“delphi”标记,因为它具有误导性。当项目索引为-1时,Lazarus会引发异常,Delphi不会。很可能,部分(或全部)
ComboBoxN.ItemIndex
返回-1(项目未选中),那么这是因为我使用Lazarus而引发的“异常”吗?(它现在起作用了)@Alberto-好吧,我不会这么说的。这是一个例外,因为项目索引无效,我想更像是这样。:)@阿尔贝托-不客气。坦率地说,我只检查了Win32小部件集。我不知道其他小部件集是否也在执行相同的检查并引发异常。对于Win32,在“TWin32ListStringList.Get”函数中引发异常。