一聚教程网:一个值得你收藏的教程网站

热门教程

VB.net中使文本框只能输入数字

时间:2022-06-25 05:35:11 编辑:袖梨 来源:一聚教程网

vb.net中使文本框只能输入数字

首先添加好文本框控件textbox后把属性imemode的值改成disable,这样在该文本框中就不能使用中文输入法了。然后对文本框的keypress事件添加以下代码

 

 private sub textbox1_keypress(byval sender as object, byval e as system.windows.forms.keypresseventargs) handles textbox1.keypress

  if char.isdigit(e.keychar) or e.keychar = chr(8) then

  e.handled = false

  else

  e.handled = true

  end if

  end sub

如果文本需要输入小数的话,就要能够输入小数点".",而且小数点只能输入一次,此时可以将上面的函数改为下面的格式:

 

 private sub textbox1_keypress(byval sender as object, byval e as system.windows.forms.keypresseventargs) handles textbox1.keypress

  if char.isdigit(e.keychar) or e.keychar = chr(8) or e.keychar = "." then

  if e.keychar = "." and instr(textbox1.text, ".") >0 then

  e.handled = true

  else

  e.handled = false

  end if

  else

  e.handled = true

  end if

  end sub

如果文本需要输入负数的话,就要能够输入负号"-",而且只能是文本框输入的第一个字符,此时又可以将上面的函数改为下面的格式:

 

 private sub textbox1_keypress(byval sender as object, byval e as system.windows.forms.keypresseventargs) handles textbox1.keypress

  if char.isdigit(e.keychar) or e.keychar = "." or e.keychar = chr(8) then

  if e.keychar = "." and instr(textbox1.text, ".") >0 then

  e.handled = true

  else

  e.handled = false

  end if

  elseif e.keychar = "-" and textbox1.text = "" then

  e.handled = false

  else

  e.handled = true

  end if

  end sub

  

这时文本框可以用来输入正的或负的整数及小数。

当有多个文本框需要做输入限制时,可以在以上代码handles后面加上多个文本框的keypress事件,各事件之间用逗号隔开,例如

  private sub textbox1_keypress(byval sender as object, byval e as system.windows.forms.keypresseventargs) handles textbox1.keypress,textbox2.keypress,textbox3.keypress

对于要判断文本框内容的函数,就要把代码进行修改,使其能够同时处理多个文本框,也就是把上面后两段程序中的textbox1.text改为ctype(sender, textbox).text,这样一来就能够对号入座了,比如上面能够输入负号的代码就可以改成:

 

 private sub textbox1_keypress(byval sender as object, byval e as system.windows.forms.keypresseventargs) handles textbox1.keypress,textbox2.keypress,textbox3.keypress

  if char.isdigit(e.keychar) or e.keychar = "." or e.keychar = chr(8) then

  if e.keychar = "." and instr(ctype(sender, textbox).text, ".") >0 then

  e.handled = true

  else

  e.handled = false

  end if

  elseif e.keychar = "-" and ctype(sender, textbox).text = "" then

  e.handled = false

  else

  e.handled = true

  end if

  

end sub

 

热门栏目