Friends,
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 can we make a TextBox accepts only numeric 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);
- }
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. Cheers!