![](/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.