如何在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
答案 0 :(得分:1)
在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 = ""
答案 1 :(得分:1)
尝试使用:
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
答案 2 :(得分:0)
试试这个:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object,ByVal e As System.EventArgs)处理TextBox1.TextChanged Dim wherePointIs As Integer = TextBox1.Text.IndexOf(“。”) 如果wherePointIs&lt;&gt; 3然后 “应该发生什么事 万一 结束子
这只会检查三点是否有点。您可以更改它,以便检查是否只有一个小数点等。