问题
I am using this code at the moment. I need to get the String value of the selected item of a ComboBox:
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;
The ComboBoxes have items inside as you can see here because I fill them in an onCreate
event of the Form5. When I press the BitBtn5 I have an error like this:

I have googled my problem and I have found the code is the same, but I have that error. Do you have any idea? (I am using lazarus 1.2.4)
回答1:
At least one of your ComboBox's item index is -1. Set them to a valid index at form creatiton, eg:
ComboBox1.ItemIndex := 0;
回答2:
I'm using Lazarus 1.4.2. The problem is that property ItemIndex is not updating when selecting items from ComboBox. To force this index to get updated I just placed some dummy code (that is accessing the ItemIndex) in OnChange event of ComboBox (see below). Then I can read ItemIndex from other places, and the value is correct.
procedure TForm1.ComboBoxChange(Sender: TObject);
var
i: integer;
begin
i := ComboBox.ItemIndex;
end;
I just encountered this problem now and I didn't find a proper solution on the internet. My post is very late but I hope this will help others.
来源:https://stackoverflow.com/questions/25675488/cannot-get-combobox-selected-item-value