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!

dharam veerPosted Aug 22, 2018, 10:03 PM
To make it more efficient because it can block other controls too you can add something ege.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
Иван КоротинPosted Jun 8, 2018, 12:43 PM
Private void textBox1_TextChanged(object sender, EventArgs e) { foreach (char c in textBox1.Text.ToCharArray()) { if (System.Text.RegularExpressions.Regex.IsMatch(c.ToString(), "[^0-9]")) { List<char> l = textBox1.Text.ToCharArray().ToList(); l.Remove(c); textBox1.Text = new string(l.ToArray()); textBox1.SelectionStart = textBox1.Text.Length; textBox1.SelectionLength = 0; } } }
safal sharmaPosted Apr 12, 2018, 4:17 AM
Thanks sir for this wonderful code
Monis AzharPosted Jun 22, 2016, 3:50 PM
This will be cool....... e.Handled = !char.IsDigit(e.KeyChar) & e.KeyChar != (char)Keys.Back;