Use regular expressions, regex, to create an efficient textbox that only takes in digits as input.

//Add to the textbox's KeyPress event
private void txtBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
e.Handled = true;
}

for controls like backspace, del, etc... use this:

if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar)) e.Handled = true;

:)

@ddanbe
Maybe you're not using the same event handler that I am.. Here's the complete code

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            //makes sure that textBox1 is a number
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar) && !char.IsPunctuation(e.KeyChar)) e.Handled = true;
        }

It works perfectly on my end.

@ai_enma
?? This snippet almost reads as vb. Use Sub End Sub instead of curly braces, and an If End If.
If that not helps you, ask in the vb.net forum.

Simplest method to use a numeric textbox which will accept the 'BackSpace' key also...

int isNum = 0;

if (e.KeyChar == '\b')
     e.Handled = false;
else if (!int.TryParse(e.KeyChar.ToString(), out isNum))
     e.Handled = true;

Edited 5 Years Ago by Ezzaral: Added code tags. Please use them to format any code that you post.

Please Help !!
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))

What does "\\d+" Means ??

Hi ddnabe,So sorry ,I didn't know about this rule .
Many Thx. for your reply ,I think this link is very useful

Note : In the keypress event of textbox type the below code


if(((int)e.KeyChar >=48 && (int)e.KeyChar <=57)||(int)e.KeyChar==08)
{

return;

}

e.Handled=true;


//Please note.The Ascii 08 is for allowing Back Space
//by Chathanz.. B-)