在选择时设置ComboBox文本

Pre*_*ias 6 delphi combobox delphi-7

我正在开发一个应用程序,其中我有一个具有长文本值的组合框.由于文本值很大(以字符... 20或更多),要在组合框中显示,要求是first在选择后显示在字符上从下拉.就像用红色标记的图像一样.如果用户选择第3项,3 0.5 to 1.25 Slight我应该只3在组合框中显示.

在此输入图像描述

所以我试过这个

   sTheSelectedValue : string;

  procedure TForm1.ComboBox1Select(Sender: TObject);
  begin
   sTheSelectedValue:=TrimTextAndDisplay(ComboBox1.Text); //send theselected value
   ComboBox1.Text :='';                                   //clear the selection
   ComboBox1.Text:=sTheSelectedValue;                     //now assign as text to combo box   
   Button1.Caption:=ComboBox1.Text;                      //just show the new value on the button.
  end;


   function TForm1.TrimTextAndDisplay(TheText : string): string;
   var
   sTheResult : string;
     begin
        sTheResult :=copy(TheText,0,1); //extract the first value..
        Result     :=sTheResult;
     end;
Run Code Online (Sandbox Code Playgroud)

结果是 在此输入图像描述

按钮似乎显示正确的值,但不显示组合框.

我想要的是进入3组合框,我似乎无法设置ComboBox1.Text:= 任何人告诉我该怎么做?像这样从组合框中选择结果应该是 在此输入图像描述

Rem*_*eau 13

我建议所有者绘制ComboBox来处理这个问题.设置TComboBox.Style属性csOwnerDrawFixed,那么就数字存储'1','2','3',等在TComboBox.Items物业本身并使用TComboBox.OnDrawItem事件以呈现完整的字符串时,在下拉列表中可见,如:

var
  sTheSelectedValue : string; 

const
  ItemStrings: array[0..7] of string = (
    '0 to 0.1 Calm (rippled)',
    '0.1 to 0.5 Smooth (wavelets)',
    '0.5 to 1.25 Slight',
    '1.25 to 2.5 Moderate',
    '2.5 to 4 Rough',
    '4 to 6 Very rough',
    '6 to 9 High',
    '9 to 14 Very high');

procedure TForm1.FormCreate(Sender: TObject);
var
  I: Integer;
begin
  ComboBox1.Items.BeginUpdate;
  try
    for I := Low(ItemStrings) to High(ItemStrings) do begin
      ComboBox1.Items.Add(IntToStr(I+1));
    end;
  finally
    ComboBox1.Items.EndUpdate;
  end;
end; 

procedure TForm1.ComboBox1Select(Sender: TObject); 
begin 
  sTheSelectedValue := IntToStr(ComboBox1.ItemIndex+1);
  Button1.Caption := sTheSelectedValue;
end; 

procedure TForm1.ComboBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
  s: String;
begin
  if odSelected in State then begin
    ComboBox1.Canvas.Brush.Color := clHighlight;
    ComboBox1.Canvas.Font.Color := clHighlightText;
  end else begin
    ComboBox1.Canvas.Brush.Color := ComboBox1.Color;
    ComboBox1.Canvas.Font.Color := ComboBox1.Font.Color;
  end;
  ComboBox1.Canvas.FillRect(Rect);
  s := IntToStr(Index+1);
  if not (odComboBoxEdit in State) then begin
    s := s + ' ' + ItemStrings[Index];
  end;
  ComboBox1.Canvas.TextRect(Rect, Rect.Left+2, Rect.Top+2, s);
  if (State * [odFocused, odNoFocusRect]) = [odFocused] then begin
    ComboBox1.Canvas.DrawFocusRect(Rect);
  end;
end;
Run Code Online (Sandbox Code Playgroud)