简体   繁体   中英

How i can use different text of item text in ComboBox in Delphi

I'm having a TComboBox component(comboxCountry) on my form. And here's the items inside the TComboBox.

Item 1 : 'Singapore SG'

Item 2 : 'India IND'

Item 3 : 'Australia AUS' and etc etc etc ..

When the combobox value is changed, i want the combboxCounty.Text to only display the country code instead of the whole String in the items list. For example, i want to only display 'SG' instead of 'Singapore SG' .. Here's how i do for cboxBankCategory OnChange function:

if comboxCountry.ItemIndex = 0 then
comboxCountry.Text := 'SG'

else if comboxCountry.ItemIndex = 1 then
comboxCountry.Text := 'IND'

else
comboxCountry.Text := 'AUS'

It seems correct, but it doesn't works for me as the comboxCountry.Text still display the whole country definition in the item list instead of only the country code, anything wrong with my code anyone ?

Thanks.

Set the combobox style to csOwnerDrawFixed , and in the onDrawItem event put this:

procedure TForm1.comboxCountryDrawItem(Control: TWinControl;
  Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
  s: String;
begin
  if not (odComboBoxEdit in State )then
    s := comboxCountry.Items[Index]
  else begin

if comboxCountry.ItemIndex = 0 then
s := 'SG'

else if comboxCountry.ItemIndex = 1 then
s := 'IND'

else
s := 'AUS'
  end;
  comboxCountry.Canvas.FillRect(Rect);
  comboxCountry.Canvas.TextOut(Rect.Left + 2, Rect.Top, s);

end;

and clear the OnChange event.

With OwnerDrawFixed style of Combobox you can use OnDrawItem event. Short example. Note that ComboBox.Text property is not changed - this method only changes how it looks.

Singapore SG
India IND
Australia AUS

procedure TForm1.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
var
  s: string;
begin
  s := ComboBox1.Items[Index];
  if odComboBoxEdit in State then
    Delete(s, 1, Pos(' ', s));  //make your own job with string
  with (Control as TComboBox).Canvas do begin
    FillRect(Rect);
    TextOut(Rect.Left + 2, Rect.Top + 2, s);
   end;
end;

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM