How to allow only numbers in a textbox in C# Windows Application ?

Want to allow the user to enter only numbers or integer values in a textbox in a C# Winforms Application ? . Below is a sample code snippet that demonstrates how to do it .

How to allow only numbers in a textbox in C# Windows Application ?

Assume that the text box name is “actxt” , we can map the Key Press event of the actxt textbox and then set e.Handled to true or false based on the character that was entered.

private void actxt_KeyPress(object sender, KeyPressEventArgs evtargs)
{
        e.Handled = (!char.IsDigit(evtargs.KeyChar)) && (!char.IsControl(evtargs.KeyChar));
}