Vejo esse tema como um assunto muito buscado por programadores, principalmente iniciantes come eu. Como se refere o título do material, tratarei de expor uma rotina que insere a vírgula em campos TEdit/TDBEdit, impedindo assim que seja digitado pelo usuário valores cujo um posterior cálculo seja executado incorretamente ou até não seja executado.
Segue Rotina:
procedure TForm1.EdtFormat(Sender: TEdit; key: char);
var
i, tam:integer;
str,str1:string;
begin
if key=#8 then
abort; //backspace
//Caso o digitado nao seja numerico = nada.
if not(key in ['0'..'9','.',',',#8,#13]) then
key := #0;
for I := 1 to length(edit1.text) do
if ((edit1.text[i]<>'.')and(edit1.text[i]<>',')) then
str:=str+edit1.text[i];
str:=str+key;
tam:=length(str);
if tam<=2 then
Str1:=','+str;
if tam=3 then
Str1:=str[1]+','+copy(str,tam-1,tam);
if tam=4 then
Str1:=copy(str,1,2)+','+copy(str,tam-1,tam);
if tam=5 then
Str1:=copy(str,1,tam-2)+','+copy(str,tam-1,tam);
if tam=6 then
Str1:=str[1]+copy(str,2,3)+','+copy(str,tam-1,tam);
if tam=7 then
Str1:=copy(str,1,2)+copy(str,3,3)+','+copy(str,tam-1,tam);
if tam=8 then
Str1:=copy(str,1,3)+copy(str,4,3)+','+copy(str,tam-1,tam);
if tam=9 then
Str1:=str[1]+copy(str,2,3)+copy(str,5,3)+','+copy(str,tam-1,tam);
if tam=10 then
Str1:=copy(str,1,2)+copy(str,3,3)+copy(str,6,3)+','+copy(str,tam-1,tam);
if tam=11 then
Str1:=copy(str,1,3)+copy(str,4,3)+copy(str,7,3)+','+copy(str,tam-1,tam);
//Atribuindo variavel ao edit.
edit1.text:=Str1;
//Foco no edit.
edit1.SetFocus;
//Finalizando rotina.
abort;
end;
Você pode utiliza-lo assim: Coloque no evento OnKeyPress do Edit/DBEdit:
if key = #13 then
begin
{No meu caso, quando é Enter no teclado, foca o Edit2}
Edit2.SetFocus;
end
else
EdtFormat(Sender as Tedit,key);
Por: ws_junior
Contato: ws_junior@hotmail.com
|