edit中只能输入数字、小数点(只可以1个小数点)和负号+多个edit共用一个事件

原来的代码无法限制只输入一个小数点

begin
     case Key of
    '0'..'9', #8, #13,#45, #27, '.' : ; //#8退格键,#13回车键
                //可输入0-9,退格,回车,点以及负号
  else
    begin
      MessageBox(0, '请输入数值!', '输入错误', MB_OK+MB_ICONERROR);
      Key := #0;
    end;
  end;
  end;

限制只输入一个小数点:

在keypress事件加入如下代码即可

if not (key in ['0'..'9','.',#8]) then
    key:=#0;
if (key='.') and (Pos('.',Edit1.Text)>0)   then
      key:=#0;

pos('.',edit1.text)得到的是 . 第一次在edit.text中出现的位置  

因为只要edit1.text中有一个 .     返回值肯定大于0

上面这段代码只能在edit1中应用,如果想将该事件应用到多个edit上,可做如下修改:(其他事件同理)

if not (key in ['0'..'9','.',#8]) then
    key:=#0;
if (key='.') and (Pos('.',TEdit(Sender).Text>0)   then
      key:=#0;

posted @ 2011-04-01 22:32  吴越  阅读(562)  评论(0编辑  收藏  举报