2015-06-18 44 views
-1

正如問題所暗示的,我需要一個文本框來允許一個小數點,它之前少於三個數字,並且只有一個數字在它之後。在VB.NET中,如何讓文本框只允許一個小數點,小於3NUMBERS,之後只有1NUMBER?

到目前爲止我已經編譯了這段代碼。

Private Sub TextBox14_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox14.KeyPress 
    Dim keyChar = e.KeyChar 

    If Char.IsControl(keyChar) Then 
     'Allow all control characters. 
    ElseIf Char.IsDigit(keyChar) OrElse keyChar = "."c Then 
     Dim text = Me.TextBox14.Text 
     Dim selectionStart = Me.TextBox14.SelectionStart 
     Dim selectionLength = Me.TextBox14.SelectionLength 

     text = text.Substring(0, selectionStart) & keyChar & text.Substring(selectionStart + selectionLength) 

     If Integer.TryParse(text, New Integer) AndAlso text.Length > 3 Then 
      'Reject an integer that is longer than 16 digits. 
      e.Handled = True 
     ElseIf Double.TryParse(text, New Double) AndAlso text.IndexOf("."c) < text.Length - 3 Then 
      'Reject a real number with two many decimal places. 
      e.Handled = True 
     End If 
    Else 
     'Reject all other characters. 
     e.Handled = True 
    End If 
End Sub 

我得到的最大問題是用戶可以輸入多個小數點,然後基本上我創建的所有規則都消失了。另外,當我想要它們時,用戶不能在小數點之前設置2個數字。

+0

你應該學習正則表達式。他們是爲此量身定製的。 – fk2

+0

我做了一年前,但我忘了他們 – 01923875v19028375v

+0

會像^ \ d +(\。\ d {1,2})?$工作?我將如何將其實施到我的代碼? – 01923875v19028375v

回答

0

用我的頭解決了它。

私人小組TextBox11_KeyPress(BYVAL發件人爲對象,BYVALË作爲System.Windows.Forms.KeyPressEventArgs)把手TextBox11.KeyPress 「什麼是允許在銷售價格文本框中鍵入 昏暗keyChar = e.KeyChar

If Char.IsControl(keyChar) Then 
     'Allow all control characters. 
    ElseIf Char.IsDigit(keyChar) OrElse keyChar = "."c Then 
     Dim text = Me.TextBox11.Text 
     Dim selectionStart = Me.TextBox11.SelectionStart 
     Dim selectionLength = Me.TextBox11.SelectionLength 

     text = text.Substring(0, selectionStart) & keyChar & text.Substring(selectionStart + selectionLength) 
     If TextBox11.Text.Contains("."c) Then 
      'Forbids a user from entering in two decimal places 
      If keyChar = "."c Then 
       e.Handled = True 
      ElseIf text.Length - text.IndexOf("."c) > 3 Then 
       e.Handled = True 
      End If 
     Else 'no decimal point currently in textbox 
      If text.Length > 5 And keyChar = ("."c) Then 'Allows only a "." to be written 
       e.Handled = False 
      ElseIf text.Length > 5 Then ' Numbers before decimal point above 99,999 
       e.Handled = True 
      End If 
     End If 
    Else 
     'Reject all other characters for this textbox. 
     e.Handled = True 
    End If 
End Sub 
相關問題