Best way to allow only numbers on a textbox

ThienZ

Freshman
Joined
Feb 10, 2005
Messages
45
Location
Germany
i tried this :
C#:
oTB.KeyPress += new KeyPressEventHandler(TextBoxNumberOnly_KeyPress);

		private void TextBoxNumberOnly_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) 
		{
			if(!Char.IsNumber(e.KeyChar)) 
			{ e.Handled = true; }
		}

but this way i can't press backspace too.... the cursor arrow and delete buttons work tho... how should i do this a better way?

thx in advanced... :)
 
this is how I do it, but in VB but maybe help you with your code because it is very similiar

Code:
  Private Sub txtCalledNumber_KeyPress(ByVal sender As System.Object, ByVal e As KeyPressEventArgs) Handles txtCalledNumber.KeyPress
        If Not Char.IsNumber(e.KeyChar) And Not Asc(e.KeyChar) = 8 Then
            e.Handled = True
        End If
    End Sub

This allows only numbers and the backspace
 
thx guys :)

now the code looks like this :
C#:
		private void TextBoxNumberOnly_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) 
		{
			if(!Char.IsNumber(e.KeyChar) && !( ((int) System.Text.Encoding.ASCII.GetBytes(e.KeyChar.ToString())[0]) == 8))
			{ e.Handled = true; }
		}

the only problem is that this code is a little slow in the first usage of escape key (it thinks about a second), but after that you notice nothing else...

maybe any other suggestions to better the running time of the code?
 
Back
Top