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

烂漫一生 提交于 2020-01-05 08:54:40

问题


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.


回答1:


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.




回答2:


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;



来源:https://stackoverflow.com/questions/11247745/how-i-can-use-different-text-of-item-text-in-combobox-in-delphi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!