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;
}

Thanks. Good one. It helped me.

this works for integer values, but not for negative and noninteger
numbers

doesnt work with back space

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

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

:)

ddanbe 2,720

Your code does not work papanyquiL, at least on my system that is.
Check out this

@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.

ddanbe 2,720

Yes! This works fine!

Use NumericUpDown control.

how about numeric textbox for vb.net

ddanbe 2,720

@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;

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

What does "\\d+" Means ??

ddanbe 2,720

Hi,islame-g, welcome here.
Please don't ressurrect old threads, read the rules!
You better start a new thread instead.
To learn about regular expressions, you could start here: http://www.regular-expressions.info/dotnet.html

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

Awsome man.. thanxxxx...

Member Avatar
sanjeewa.abeywardana

wow, wonderful areas to read . thanks for every ideas given

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-)