Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Начинающим";
Текущий архив: 2008.03.23;
Скачать: [xml.tar.bz2];

Вниз

Вопрос про 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;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.49 MB
Время: 0.015 c
2-1204115259
Darvin
2008-02-27 15:27
2008.03.23
TCanvas и регионы


3-1193337794
DiX
2007-10-25 22:43
2008.03.23
Изменения отображения в DBGrid


15-1202824478
Iam
2008-02-12 16:54
2008.03.23
Бесплатная междугородняя IP-телефония


2-1203981931
AlexGTI
2008-02-26 02:25
2008.03.23
Окна


8-1177944957
Nikss
2007-04-30 18:55
2008.03.23
OpenGL





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский