June 2, 2015 by Nitesh

How To Create a TextBox Accepting Only Numbers in Windows Forms


Many times we need to have a textbox on our windows forms where we need to accept only numbers from the end users. .Net does provide us a NumericUpDown control but it is not always handy. In this post, we will see how we can create a TextBox accepting only numbers in Windows Forms for entries.

To enable any TextBox number only, handle the “KeyPress” event handler of the TextBox and write the below code in the handler. Considering the ID of TextBox control is txtNumeric, the code will be like as below –

        private void txtNumeric_KeyPress(object sender, KeyPressEventArgs e)
            e.Handled = !char.IsDigit(e.KeyChar); //&& !char.IsControl(e.KeyChar);

In VB.Net, the same code can be written as below –

        Private Sub txtNumeric_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles txtNumeric.KeyPress
            e.Handled = Not char.IsDigit(e.KeyChar)
        End Sub

If you see the code above, we have checked if the entered character is a number or not and have manually marked the Handled property of the event handler to true.

Hope you like this post. Cheers!


Support us!

If you like this site please help and make click on any of these buttons!

Powered by WordPress Popup