Saturday, August 21, 2010

In VB.NET, how can I restrict the characters of a text box to numbers and control buttons only?

In VB.NET, how can I restrict the characters of a text box to numbers and control buttons (i.e Delete, backspace...) only?In VB.NET, how can I restrict the characters of a text box to numbers and control buttons only?
Use this event handler:





Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress


Dim c As Char


c = e.KeyChar


If Not (Char.IsDigit(c) Or Char.IsControl(c)) Then


e.Handled = True


End If


End SubIn VB.NET, how can I restrict the characters of a text box to numbers and control buttons only?
you need to use the masked text box





sorry i don't know what you should do for the other part
Look into regular expressions. It will help you restrict whatever you want.
Solution 1:


========


Use a MaskedTextBox and set the ';mask'; property to ';9999999';





Try it and check if it behaves like you want (personally I don't like it)





Solution 2


=======


Or you could use an ordinary ';TextBox'; with the following handler to trap the TextChanged event and detect any non digit character





Dim oldText As String





Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged


Dim digitFound As Boolean


Dim textLength As Int16


Dim i As Int16





digitFound = True


textLength = TextBox1.Text.Length


i = 0


While (digitFound = True And i %26lt; textLength)


digitFound = Char.IsDigit(TextBox1.Text, i)


i = i + 1


End While


If digitFound = False Then


Dim caretPosition As Int16


caretPosition = TextBox1.SelectionStart


TextBox1.Text = oldText


TextBox1.SelectionStart = caretPosition - 1


Else


oldText = TextBox1.Text


End If


End Sub
  • makeup help
  • No comments:

    Post a Comment