Mega Code Archive

 
Categories / Delphi / VCL
 

TEdit with auto complete feature added

Title: TEdit with auto-complete feature added Question: An auto-complete feature can be added to a TEdit component by handling the keyUp event. This is a simple approach that gives complete control to the programmer. Answer: // See Delphi3000 article 1533 for auto-complete component // To add auto-complete capability to a TEdit component // 1) Declare a global TStringlist object // 2) Create it on the form create event // 3) Free it on the form destroy event // 4) Add new entry to it on the TEdit exit event // 5) Do the auto-complete on the TEdit keyUp event // 6) Add a TCheckbox control for enable/disable // If desired, initialize the list from a database, ini file etc. procedure TForm1.FormCreate(Sender: TObject); begin listValues := TStringList.create; listValues.sorted := true; listValues.Duplicates := dupIgnore; end; procedure TForm1.FormDestroy(Sender: TObject); begin listValues.free; end; procedure TForm1.edtListExit(Sender: TObject); begin listValues.add(edtList.text); end; procedure TForm1.edtListKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var theText: string; i, p: integer; begin if not ckbxList.checked then exit; // User can enable/disable with edtList do case key of 8, 13, 46, 37..40: ; // No backspace, enter, delete, or arrows else begin // Search for unselected portion at start of text p := selStart; // cursor position theText := copy(text, 0, p); // Excludes searched portion // Match entered text portion for i := 0 to listValues.count-1 do begin // Keep case of listed item if pos(upperCase(theText), upperCase(listValues[i]))=1 then if compareText(theText, listValues[i]) begin text := listValues[i]; selStart := p; SelLength := length(text) - selStart; break; // Match found, so quit search end; end; // for end; // case end; // with end;