2011-11-09 41 views
0

如何在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 
+1

Metro?的WinForms? WPF? Silverlight的? ASP.Net? MonoTouch的? – SLaks

+0

它是一個Windows應用程序。在Visual Studio中使用vb.net – Kurusu

+1

WinForms或WPF或Metro? – SLaks

回答

1

在的WinForms,你可以通過使用文本框的框TextChanged,事件和RegularExpressions做到這一點:

例子:

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 

這個例子可以讓你寫123345.12.123.1123.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}))$"允許小數
  • 更正while循環條件後的數字從Textbox1.Text = ""strText = ""
+0

這太棒了!但我也需要它輸入小數點後兩位或三位數字...... – Kurusu

+0

@Kurusu編輯示例。我希望它按預期工作;) – Nicholas

+1

@Kurusu:在你的問題中你說過「在輸入三位數字後我只允許一個小數點」。但是現在你說在小數點後面輸入更多的數字是可以的。所以你的問題不是很清楚。 –

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 
0

嘗試這種情況:

私人小組TextBox1_TextChanged(BYVAL發件人爲System.Object的,BYVALË作爲System.EventArgs)把手TextBox1.TextChanged 昏暗wherePointIs爲整數= TextBox1.Text.IndexOf(」。 「) 如果wherePointIs <> 3然後 「請告訴我應該發生 結束如果 結束小組

此,如果有三個點的點僅檢查。您可以更改它,以便檢查是否只有一個小數點等。

相關問題