2

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:

enter image description here

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)

Alberto Rossi
  • 1,800
  • 4
  • 36
  • 58

2 Answers2

2

At least one of your ComboBox's item index is -1. Set them to a valid index at form creatiton, eg:

ComboBox1.ItemIndex := 0;
Sertac Akyuz
  • 54,131
  • 4
  • 102
  • 169
  • So is this an "exception" because I am using Lazarus? (It works now) – Alberto Rossi Sep 04 '14 at 21:57
  • 1
    @Alberto - Well, I wouldn't put it that way. This is an exception because item index is not valid is more like it I guess. :) – Sertac Akyuz Sep 04 '14 at 21:58
  • 1
    @Alberto - You are welcome. To be frank I only checked the Win32 widget set. I don't actually know if other widget sets are doing the same check and raising the exception. For Win32, exception is raised in 'TWin32ListStringList.Get' function. – Sertac Akyuz Sep 04 '14 at 23:56
1

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.

Dani
  • 21
  • 3