Главная страница
Top.Mail.Ru    Яндекс.Метрика
Текущий архив: 2008.03.23;
Скачать: CL | DM;

Вниз

Вопрос про TEdit. Как отследить ввод тока цифр.   Найти похожие ветки 

 
vegarulez ©   (2008-02-21 09:23) [0]

привет всем!
Делаю так:

procedure TForm1.Edit3KeyPress(Sender: TObject; var Key: Char);
begin
try
if (strtoint(key) in [0..9]) then
 label3.Caption:="!";
except
key:=chr(0);
end;

end;


но тут есть маленькая загвоздка.... например при нажатии BackSpace т.е. стереть я не могу... так как  BackSpace это  key:=#8.

Подскажите как сделать по уму... а не так как я пытаюсь это реализовать через strtoint... а то условие не получается объеденить по or... типа: if ((strtoint(key) in [0..9]) or (key=#8))...


 
KilkennyCat ©   (2008-02-21 09:25) [1]

0..9, #8


 
KilkennyCat ©   (2008-02-21 09:27) [2]

точнее ["0".."9", #8]


 
vegarulez ©   (2008-02-21 09:28) [3]

KilkennyCat ©   (21.02.08 09:25) [1]

Всмысле?
Key: Char
...
поподробнее если можно... для особо тупых...


 
KilkennyCat ©   (2008-02-21 09:29) [4]

if (key in ["0".."9", #8]) then


 
vegarulez ©   (2008-02-21 09:29) [5]

KilkennyCat ©   (21.02.08 09:27) [2]
а... ну так да. понел.


 
vegarulez ©   (2008-02-21 09:30) [6]

KilkennyCat ©   (21.02.08 09:29) [4]
да. фсё... ужо понел. псп.
проблема решена.


 
Dennis I. Komarov ©   (2008-02-21 09:34) [7]

Paste...


 
Рамиль ©   (2008-02-21 09:38) [8]

Надо вешать на OnChange, запоминая каждый раз значение и возвращать его, если получается не то что надо (самый простой рабочий вариант)


 
ЮЮ ©   (2008-02-21 09:40) [9]

На уровене компонетов JVCL это сделано так:
полагаю сможещь подобное сделать в обработчике OnKeyPress

//=== TCustomIntegerEdit =====================================================

procedure TCustomIntegerEdit.KeyPress(var Key: Char);
var
 lsNewText: string;
begin
 { not interested in control chars }
 if Ord(Key) < Ord(" ") then
 begin
   if Key = #13 then
     Key := #0
   else
     inherited KeyPress(Key);
   Exit;
 end;

 { allow only digits and minus sign }
 if not CharIsDigit(Key) and (Key <> "-") then
   Key := #0;

 if Key = "-" then
 begin
   { are any neg. numbers in range ? }
   if HasMinValue and (MinValue >= 0) then
     Key := #0
   { minus sign only as first Char }
   else
   if SelStart <> 0 then
     Key := #0;

   { only 1 minus sign }
   if StrLeft(lsNewText, 2) = "--" then
     Key := #0;
 end;

 { no leading zeros }
 if (SelStart = 0) and (Key = "0") and (StrLeft(lsNewText, 1) = "0") then
   Key := #0;

 { no leading "-0" }
 if (SelStart = 1) and (Key = "0") and (StrLeft(lsNewText, 2) = "-0") then
   Key := #0;

 { disallow the keypress if the value would go out of range }
 lsNewText := GetChangedText(Text, SelStart, SelLength, Key);
 if not IsInRange(lsNewText) then
   Key := #0;

 if Key <> #0 then
   inherited KeyPress(Key);
end;

procedure TCustomFloatEdit2.KeyPress(var Key: Char);
var
 lsNewText: string;
 iDotPos: Integer;
begin
 { not intersted in control chars }
 if (Ord(Key)) < Ord(" ") then
 begin
   inherited KeyPress(Key);
   Exit;
 end;

 { allow only digits, "." and minus sign }
 if not CharIsNumber(Key) then
   Key := #0;

 if Key = "-" then
 begin
   { are any neg. numbers in range ? }
   if HasMinValue and (MinValue >= 0) then
     Key := #0
   { minus sign only as first Char }
   else
   if SelStart <> 0 then
     Key := #0;

   { only 1 minus sign }
   if StrLeft(lsNewText, 2) = "--" then
     Key := #0;
 end;

 { no leading zeros }
 if (SelStart = 0) and (Key = "0") and (StrLeft(lsNewText, 1) = "0") then
   Key := #0;

 { no leading "-0" }
 if (SelStart = 1) and (Key = "0") and (StrLeft(lsNewText, 2) = "-0") then
   Key := #0;

 iDotPos := Pos(".", Text);

 if Key = "." then
 begin
   { allow only one dot, but we can overwrite it with another }
   if (iDotPos > 0) and not ((SelLength > 0) and (SelStart <= iDotPos) and ((SelStart + SelLength) >= iDotPos)) then
     Key := #0
 end;

 { check number of decimal digits }
 if (iDotPos > 0) and (SelStart > iDotPos) and
   ((Length(Text) - iDotPos) >= MaxDecimals) then
 begin
   Key := #0;
 end;

 { disallow the keypress if the value would go out of range }
 lsNewText := GetChangedText(Text, SelStart, SelLength, Key);
 if not IsInRange(lsNewText) then
   Key := #0;

 if Key <> #0 then
   inherited KeyPress(Key);
end;


 
KilkennyCat ©   (2008-02-21 10:10) [10]

жуть.


 
vegarulez ©   (2008-02-21 10:16) [11]

нда... чото ЮЮ ты нагороди[л\ла (нужное подчеркнуть)]

я сделал вот так:

if not (key in ["0".."9",#8]) then
 key:=chr(0);

и забиндил все эдиты, где нужна проверка, на эту процедурку...всё работает...


 
engine ©   (2008-02-21 10:23) [12]

> [11] vegarulez ©   (21.02.08 10:16)

ctrl+C/ctrl+v


 
vegarulez ©   (2008-02-21 10:24) [13]

неа... у меня токова впринципе быть не могёт...


 
ЮЮ ©   (2008-02-21 12:33) [14]

> неа... у меня токова впринципе быть не могёт...


пользователь две клавиши срвзу нажать не в силах?


> нда... чото ЮЮ ты нагороди[л\ла (нужное подчеркнуть)]
>
> я сделал вот так:


Обычно приходится вводить числа, а это несколько болеше, чем последовательность цифр. Если же тебя интересуют цифры, только цифры и ничего кроме цифр, твды да.
Особенно в свете  а то условие не получается объеденить по or... типа: if ((strtoint(key) in [0..9]) or (key=#8))... :)


 
Ega23 ©   (2008-02-21 17:31) [15]


> нда... чото ЮЮ ты нагороди[л


Это как раз тот самый универсальный код. Защищает и от Copy-Paste
Но. Не защищает от того, что я вообще ничего туда не введу.  :)


 
Loginov Dmitry ©   (2008-02-21 21:41) [16]

Проверять на OnChange нужно.


 
engine ©   (2008-02-21 21:42) [17]

> [16] Loginov Dmitry ©   (21.02.08 21:41)

Или на OnExit



Страницы: 1 вся ветка

Текущий архив: 2008.03.23;
Скачать: CL | DM;

Наверх




Память: 0.51 MB
Время: 0.015 c
4-1178650355
Strate
2007-05-08 22:52
2008.03.23
Опять ListView, изменение колонки.


2-1203928808
User123
2008-02-25 11:40
2008.03.23
procedure TForm1.Edit1Change(Sender: TObject);


11-1186278717
ElectriC
2007-08-05 05:51
2008.03.23
Проблем-ка с TIcon


15-1202605179
Linker
2008-02-10 03:59
2008.03.23
Когда я пишу const aRecord в параметре функции, то туда передаётс


15-1202629339
@!!ex
2008-02-10 10:42
2008.03.23
Редактирование видео