FireMonkey TComboBox Bypasses Safety And Creates An Access Violation

First, I love Delphi (20 years use) and FireMonkey (5 years use – Android).  My thoughts are criticisms, not a rejection.

Delphi VCL TComboBox handles no ItemIndex (-1) selected beautifully.  FireMonkey not so easily.  In fact if you handle things wrong,  you can create an access violation which is bad news.

I first encountered this during my first FireMonkey project.  The result was a big WHAT!!!  Honestly, it took me a while to absorb this.

VCL project:

procedure TForm1.Button1Click(Sender: TObject);
begin
    ComboBox1.ItemIndex := -1;
    Label1.Caption := EmptyStr;
end;

procedure TForm1.ComboBox1Change(Sender: TObject);
begin
    Label1.Caption := ComboBox1.Items[ComboBox1.ItemIndex];
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
    combobox1.items.Add(‘1’);
    combobox1.items.Add(‘2’);
    combobox1.items.Add(‘3’);
end;

Selecting a combobox item shows the value in the label.  Clicking the button clears the item and removes the labels caption.  As designed!!!  Note: You have to remove the label caption.  Safety first.

FireMonkey project:

procedure TForm1.Button1Click(Sender: TObject);
begin
    combobox1.ItemIndex := -1;
end;

procedure TForm1.ComboBox1Change(Sender: TObject);
begin
    Text1.Text := combobox1.items[combobox1.ItemIndex];
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
    combobox1.items.Add(‘1’);
    combobox1.items.Add(‘2’);
    combobox1.items.Add(‘3’);
end;

Notice it is the exact code.  Selecting a combobox item shows the value in the textbox.  Clicking the button clears the item; however, putting a -1 in the combobox1.items produces the access violation.  FireMonkey did not adhere to safety first.

To correct this you have to do the following:

procedure TForm1.ComboBox1Change(Sender: TObject);
begin
    if ComboBox1.ItemIndex = -1 then
        Text1.Text := EmptyStr
    else
        Text1.Text := combobox1.items[combobox1.ItemIndex];
end;

You have to check as to whether of not the combobox has an item selected.  No more access violation.  Note: FireMonkey does handle removing the text from the textbox; however, you have to account for the combobox having no selected item.

To be continued.