2012-10-21 16 views
5

Im新增visual basic和im不確定如何禁用字母和特殊字符。禁用Visual Basic.NET中的字母和特殊字符

我只希望用戶能夠輸入數字。

即時通訊使用此代碼即時知道還有一個更簡單的方式來做到這一點,所有的幫助表示讚賞

我得到的消息框,當我輸入字母字符,當我輸入數字。當我輸入數字時,我不想要消息框。

Private Sub txtCustom_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtCustom.KeyDown 

    If (e.KeyCode = Keys.Enter) Then 

     e.SuppressKeyPress = True 

     If (e.KeyCode = Keys.A Or Keys.B Or Keys.C Or Keys.D Or Keys.E Or Keys.F Or Keys.G Or Keys.H Or Keys.I Or Keys.J Or Keys.K Or Keys.L Or Keys.M Or Keys.N Or Keys.O Or Keys.P Or Keys.Q Or Keys.R Or Keys.S Or Keys.T Or Keys.U Or Keys.V Or Keys.W Or Keys.X Or Keys.Y Or Keys.Z) Then 

      Beep() 
      MsgBox("Please Input A Numerical Value") 
      txtCustom.Text = "" 

     Else 

      RandNumAllow = txtCustom.Text 

     End If 

    End If 

End Sub 
+1

這段代碼的價值似乎只有當你鍵入回車鍵,在這種情況下,字符不能是字母工作。你確定發佈了正確的代碼嗎? – Steve

+1

沒有什麼比這樣懲罰用戶的程序更煩人了。這就像應用小電擊,您的用戶會很快厭倦它。相反,使用驗證事件,例如Decimal.TryParse()來檢查輸入。和ErrorProvider提供一個微妙的錯誤指示。 –

回答

7

嘗試使用KeyPress事件而不是:

Private Sub TextBox1_KeyPress(sender As Object, _ 
           e As KeyPressEventArgs) Handles TextBox1.KeyPress 
    e.Handled = Not Char.IsNumber(e.KeyChar) 
End Sub 

但這不會使用剪貼板阻止別人。相反,使用MaskedTextBox控件可能會更好。

+0

我決定使用一個蒙面的文本框,感謝您的幫助,它不完全是我想要的,但是謝謝它快得多 –

+0

這不會阻止(襯衫+數字)特殊字符。 – jcaruso

+0

這也將禁用刪除和退格空間,它們如何啓用? –

1

對不起,遲到的迴應此代碼將解決所有問題,從剪貼板複製和Shift +數字爲特殊字符,因爲它使用TextChanged事件試用它。

Dim charactersAllowed As String = "1234567890" 
     Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged 
    Dim theText As String = TextBox1.Text 
    Dim Letter As String 
    Dim SelectionIndex As Integer = TextBox1.SelectionStart 
    Dim Change As Integer 
    For x As Integer = 0 To TextBox1.Text.Length - 1 
     Letter = TextBox1.Text.Substring(x, 1) 
     If charactersAllowed.Contains(Letter) = False Then 
      SystemSounds.Beep.Play() 
      theText = theText.Replace(Letter, String.Empty) 
      Change = 1 
     End If 
    Next 
    TextBox1.Text = theText 
    TextBox1.Select(SelectionIndex - Change, 0) 
End Sub 

可以替換charractersAllowed與任何你想要的字符,可以讓