Numbers only textbox

Michael27 2 Tallied Votes 244 Views Share

This sets the textbox for only numbers

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            char c = e.KeyChar;
            //c == 8 is Backspace
            //c == 32 is Space
            //c == 13 is Carriage return (Enter)
            // http://www.asciitable.com/ Tabel of ascii characters
            if ((Char.IsDigit(c) || c == 8) || c == 32 || c == 13) return; 
            e.Handled = true; //
        }
Mike Askew 131 Veteran Poster Featured Poster

Useful to know :)

Momerath 1,327 Nearly a Senior Poster Featured Poster

What about negative numbers, or numbers with decimal points? And what number has a space in it?

Michael27 29 Newbie Poster

For a numbers with decimal point you add c == 46 and for negative numbers use c == 45

Momerath 1,327 Nearly a Senior Poster Featured Poster

If I do that, then -384.2834-234.20394 becomes acceptable, and that isn't a number!

And why are you using the magic numbers rather than the Keys enumeration.

Michael27 29 Newbie Poster

I didn't know about Keys enumeration.
Thanks.

ddanbe 2,724 Professional Procrastinator Featured Poster

Sorry for the late response, (I was quite ill lately) I once wrote this snippet: http://www.daniweb.com/software-development/csharp/code/217265/capturing-numeric-input-in-a-textbox

Codefiva 0 Newbie Poster

Regexpression can be used to accomplish this variety of options.

RichardCh 0 Newbie Poster

easy:

<input  type="text" onkeyup="this.value=this.value.replace(/[^\d]/,'');">
Michael27 29 Newbie Poster

This is not ASP

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.