Link to home
Start Free TrialLog in
Avatar of Asw
Asw

asked on

Locate Item In ComboBox

Hi,

I have a combobox in which I load 100
items, the items are all parts with a starting code of say 'ABC Motor.'.

If at runtime I type 'A' in the combobox I want the the combobox to go to the nearest of the items just like Table.GoToNearest;.

How can I do this.

Asw
Avatar of TheNeil
TheNeil

Easy - just add the following to the OnKeyUp method of your ComboBox.

VAR
  n : INTEGER;
  New_Text : STRING;
begin
  New_Text := '';
  FOR n := 0 TO (ComboBox1.Items.Count - 1)
  DO
    IF Pos(ComboBox1.Text, ComboBox1.Items[n]) = 1
    THEN
      New_Text := ComboBox1.Items[n];

  IF New_Text <> ''
  THEN
    ComboBox1.Text := New_Text;
end;

The code will search through the items and select the one that matches. If it can't find it then the text in the ComboBox is unaffected

The Neil
Hi,
    U r asking for something like a lookupcombo box. There is a TDBLookupcombo. And we have a lot of 3rd party comps for it. Go to Delphi mag or about.delphi.com and look for the com. Or in ur query use Name like A% & fill up the box again.
                                                          All the best
                                                             Manju
Hi Asw,

Try this piece of code and you will get BACKSPACE working too:

procedure TForm1.ComboBox1Change(Sender: TObject);
var
  TmpText : string;
  i : integer;
begin
  with TComboBox(Sender) do begin
    TmpText := Text;  // save the text that was typed by the user
    for i := 0 to Items.Count - 1 do begin
      if Pos(Text, Items[i]) = 1 then  begin
        ItemIndex := i;
        SelStart := Length(TmpText);
        SelLength := Length(Items[i]) - Length(TmpText);
        Break;
      end;
    end;
  end;
end;

procedure TForm1.ComboBox1KeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #8 then begin
    with TComboBox(Sender) do begin
      Text := Copy(Text, 1, Length(Text) - SelLength - 1);
    end;
    ComboBox1Change(Sender);
    Key := #0;
  end;
end;

Regards, Geo
Avatar of Asw

ASKER

Hi Chaps,

Many thanks for all the comments.

I have to give the points to the procedure I used, so geobul if you could post your comment a an ansewer I shall give you the points.

Many Thanks

Andy
ASKER CERTIFIED SOLUTION
Avatar of geobul
geobul

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial