![](/img/trans.png)
[英]In VB.NET how do I get a textbox to only allow one decimal point, < 3NUMBERS before it, and only 1NUMBER after it?
[英]Allow only a decimal point after an input of three digits in a textbox in VB.NET?
在VB.NET的文本框中输入三位数后,如何只允许小数点?
假设我输入了“123”,之后我只能输入小数,否则它不会允许任何其他输入。 结果就是“123”。
Dim KeyAscii As Integer
KeyAscii = Asc(myE.KeyChar)
Select Case KeyAscii
Case Asc("0") To Asc("9"), Asc(ControlChars.Back)
myE.Handled = False
Case Asc(".")
If InStr(myTextbox.Text, ".") = 0 Then
myE.Handled = False
Else : myE.Handled = True
End If
Case myE.KeyChar = Chr(127)
myE.Handled = False
Case Else
myE.Handled = True
End Select
在WinForms中,您可以通过使用Textbox和RegularExpressions的TextChanged-Event来完成此操作:
例:
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
'** Regex Pattern
Dim pattern As String = "^(([0-9]{1,3})|([0-9]{1,3}(\.){1,1}([0-9]){0,3}))$"
'** Copy of the Textbox Content
Dim strText As String = TextBox1.Text
'** Remove chars at the end of the string until the Textbox is empty or the contained chars are valid
While Not Regex.IsMatch(strText, pattern) AndAlso Not strText = ""
strText = strText.Substring(0, strText.Length - 1)
End While
'** Set the new text
TextBox1.Text = strText
'** Set the caret to the end of the string in the textbox
TextBox1.Select(TextBox1.Text.Length, 0)
End Sub
End Class
这个例子可以让你写123
, 345.
, 12.
, 123.1
, 123.123
等等...
要改善小数点前后的位数,可以编辑模式中的{0,3}
(前两次是小数点前的数字,第三次是小数点后的数字)。 只需设置您喜欢的数字而不是3(或用*
或{0,}
代替无限制)
希望这可以帮助。
编辑1:
"^[0-9]{0,3}(\\.){0,1}$"
更改为"^(([0-9]{1,3})|([0-9]{1,3}(\\.){1,1}([0-9]){0,3}))$"
允许小数点后的数字 Textbox1.Text = ""
到strText = ""
尝试使用:
Select Case myE.KeyChar
Case "0"c To "9"c, "."c
myE.Handled = InStr(myTextbox.Text, ".") > 0
Case ControlChars.Back, Convert.ToChar(127)
myE.Handled = False
Case Else
myE.Handled = True
End Select
注意:将KeyChar转换为Integer并使用Asc()进行比较是没有意义的。
编辑 :根据您的评论,小数点必须放在第三个数字后面,并且可以跟随2或3个数字。
Select Case myE.KeyChar
Case "0"c To "9"c
myE.Handled = myTextbox.Text.Length = 3 OrElse myTextbox.Text.Length >= 7
Case "."c
myE.Handled = myTextbox.Text.Length <> 3
Case ControlChars.Back, Convert.ToChar(127)
myE.Handled = False
Case Else
myE.Handled = True
End Select
尝试这个:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object,ByVal e As System.EventArgs)处理TextBox1.TextChanged Dim wherePointIs As Integer = TextBox1.Text.IndexOf(“。”)if wherePointIs <> 3那么'什么应该发生结束If结束子
这只会检查三点是否有点。 您可以更改它,以便检查是否只有一个小数点,等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.