How To Create a TextBox Accepting Only Numbers in Windows Forms

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 –

  1. private void txtNumeric_KeyPress(object sender, KeyPressEventArgs e)  
  2. {  
  3.            e.Handled = !char.IsDigit(e.KeyChar);

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

  1. Private Sub txtNumeric_KeyPress(ByVal sender As ObjectByVal e As KeyPressEventArgs) Handles txtNumeric.KeyPress  
  2.            e.Handled = Not char.IsDigit(e.KeyChar)  
  3. 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!

Rebin Infotech
Think. Innovate. Grow.