Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

control input into TEdit

Status
Not open for further replies.

hayate

Programmer
May 17, 2003
7
JP
Hi,

With TEdit, I want to put '-' just before and after numbers like that.
-123 or 123-
NOT like -12-3, 123--, -123-

I wrote the code provided below but this one can control '-' put only before numbers.

(OnKeyPress event)
if (Key = '-') and (Edit1.SelStart <> 0) then
begin
Key := #0;
end;

I want to improve or rewrite the code so that '-' can be put just after numbers too.
Is it possible?

Thank you in advance !



 
Code:
if (Key = '-') and ((Edit1.SelStart <> 0) and (Edit1.SelStart <> Length(Edit.Text) - 1)) then 
begin
    Key := #0;
end;

Cheers
 
I think that Richard's code would allow numbers to be entered after a trailing minus sign which is probably not what you want.

So I would suggest that you modify the OnKeyPress event handler to something like:
Code:
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
var
  p: integer;
  len: integer;
begin
  if key = #8 then exit;         // Allow Backspace at any time

  p := Pos ( '-', Edit1.Text );
  len := Length(Edit1.Text);

  if ( p > 1 ) and ( len > 0 ) then
    key := #0

  else if key = '-' then begin
    if p > 0 then
      key := #0
    else if ( Edit1.SelStart <> 0 ) and ( Edit1.SelStart <> len ) then
      key := #0
  end
end;

Andrew
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top