2016-08-15 20 views
-7

我想輸入數字只有並且不允許非數字,請幫助我這個。只允許WPF中的密碼框中的數字

這段代碼在文本框不過,這並不與PasswordBox

 Dim textBox As TextBox = TryCast(sender, TextBox) 
     Dim selectionStart As Int32 = textBox.SelectionStart 
     Dim selectionLength As Int32 = textBox.SelectionLength 
     Dim newText As [String] = [String].Empty 
     Dim count As Integer = 0 
     For Each c As [Char] In textBox.Text.ToCharArray() 
      If [Char].IsDigit(c) OrElse [Char].IsControl(c) Then 
       newText += c 
      End If 
     Next 
     textBox.Text = newText 
     textBox.SelectionStart = If(selectionStart <= textBox.Text.Length, selectionStart, textBox.Text.Length) 

工作謝謝

+0

你爲什麼不把你到目前爲止試過嗎?關閉我的頭頂,我會讓密碼框訂閱keyup和keydown事件,如果最後一個字符是數字選項,您可以在那裏檢查。 –

+0

我把代碼與我一起工作在TextBox – shhada

回答

0
Private Sub PbPhone_PreviewTextInput(sender As Object, e As TextCompositionEventArgs) Handles PbPhone.PreviewTextInput 
    Dim regex As New Regex("[0-9]+") 
    If Not regex.IsMatch(e.Text) Then 
     e.Handled = True 
    End If 
End Sub 
+1

關心解釋 –

+0

以前的代碼只會接受數字,雖然引入了一個字符,你不會寫 – shhada

+0

對不起,謝謝 – shhada