I want allow only to enter numeric values in a textbox in C#. Can someone assist me on this. would be a great help.

Sink the KeyDown event for the text box and you can cancel key presses if the character typed is not a digit. In fact, the documentation example for Control.KeyDown does exactly what you want.

You are both going about it a really long way, and it will make the program slower. Add a masked textbox, and set the mask to numeric only, or just add a numeric up-down.

> You are both going about it a really long way, and it will make the program slower.
The difference between a MaskedTextBox, a NumericUpDown, and a TextBox with a hooked event will usually be negligible in an I/O bound form.

That is only for straight numeric input where NumericUpDown and MaskedTextBox work perfectly. For any kind of complicated formatting, Edward still usually prefers manual parsing and formatting in a TextBox because the MaskedTextBox cannot handle simple jobs like trimming the value in a currency mask. The code is harder to write and maintain, but the result is more professional and easier on users.

> Add a masked textbox, and set the mask to numeric only, or just add a numeric up-down.
The question was how to restrict input to numerics with a TextBox control, not the best way to take numeric input on a form. ;)

Hello,

I use a variety of methods all with Regex.

To use this you will need to add the namespace

using System.Text.RegularExpressions;

Firstly the KeyPress Event

private void txtStockBought_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsNumber(e.KeyChar))
            {
                if (Regex.IsMatch(txtStockBought.Text, "\\D+"))
                {
                    e.Handled = true;
                }
            }
            else
            {
                e.Handled = e.KeyChar != (char)Keys.Back;
            }

you will also need to add it to the form control events KeyPress

If you want to expand to numbers for purchase amounts then use this method

private void txtForPurchases_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsNumber(e.KeyChar) || e.KeyChar == '.' || e.KeyChar == '£')
            {
            }
            else
            {
                e.Handled = e.KeyChar != (char)Keys.Back;
            }

and include a Regex validator

Private string Validate()
{
     if (Regex.IsMatch(txtForPurchases.Text, "^\\£?[+-]?[\\d,]*\\.?\\d{0,2}$"))
     {

     }
}

I'm having a problem with starting with KeyPress event. The program is derecting me to the TextChanged event. How to change it to the KeyPress event.

I'm having a problem with starting with KeyPress event. The program is derecting me to the TextChanged event. How to change it to the KeyPress event.

I'm sure the purists are howling, but I say Keep the TextChanged event. use
if (!int.TryParse(My_tbx.Text, out i) {//Error handling block } where "i" is int.

You can do this with any numeric type.

You may want to check for negative numbers or see how uint handles negative numbers.

PS I personally hate the new Daniweb. It has so far thrown me out 3 times and I've resorted to using notepad so I can keep what I've typed when it throws me out again.

I'm having a problem with starting with KeyPress event. The program is derecting me to the TextChanged event. How to change it to the KeyPress event.

Hello,

you need to change it manually, so when you double click your textbox you get the TextChanged Event, correct?

once this happens just change the _TextChanged to _KeyPress, and the same with the event args.

Basically just copy my KeyPress event block and change the textbox name to yours.

Don't forget that once you add it you will need to go to your Textbox Properties > Events > KeyPress to activate this method as well.

For validation purpose in your project at some places you put text boxes that accept only integer value i.e. 1, 20 , 50, 200 etc... To put validation on that text boxes and allow only integer value you can use ASP.NET Regular Expression Validator Control.
Click Here to view example.

link : http://jayeshsorathia.blogspot.com/2012/10/allow-only-integer-value-in-textbox-using-regular-expression-validator-control.html

commented: It's a 2 year old post, and shameless self-promotion... tisk tisk. -1

Ap0ca1ypse's code is perfect for this purpos, but if you don't want to use these code because of troubling keypress Event "YOu Can Use this simple code for Text validation "

 private void button8_Click(object sender, EventArgs e)
        {
            try
            {
                if (Convert.ToInt32(textbox1.Text) < 0)
                {
                    MessageBox.Show("Please Enter Correct Value !", "Information");
                    textbox1.Text = "0";
                    textbox1.Focus();
                }
            }
            catch
            {
                MessageBox.Show("Enter Only Numaric Value !", "Information");
                textbox1.Text = "0";
                textbox1.Focus();
            }
        }

I hope this will help You.

kimbula last posted 2 years ago, hasn't responded to suggestions since. Why would (s)he care about suggestions now? My suggestion 2 years ago avoids all the try/catch logic because it is encapsulated in int.TryParse. (Still need error handling, but number handling is built into the numbers themselves. Seems dumb to use anything else when built-in functionality comes directly from .NET.)

Help whom? The original poster is 3 years gone.
I certainly would be pissed at a control that didn't let me use the arrow keys, the backspace key, the delete key. Those are part and parcel of a numeric entry. What if the number is real? How about negative numbers?
Personally, I like to be told after the fact that I screwed up, not the machine going dead with no clue what I'm screwing up.

commented: Good point! +15

Sorry for being so discourtious, you're right, it's obvious my brain opperates at a different level.

Help whom? The original poster is 3 years gone.

The original poster isn't the only person a thread might help, that's why we don't close threads after they reach a certain age.

It could be helpful for u if u had brain.

Malicious personal attacks will not be tolerated, please keep our rules in mind.

cuz you dont own this community........

Nor do you. It's generally frowned upon when a new member tries to play net nannie. I'd suggest that if you feel any rules are broken, simply report the offending post and let those of us who were selected by the owner of this community to enforce those rules handle it. Taking matters into your own hands is a good way to find yourself in the wrong and subject to moderator action.

commented: Thanks, for how you handled both of us because we were both wrong in how we reacted. I later felt an idiot for reacting to a post. +3

deceptikon: I noticed your tag line:
"Respect is like a punch to the face. If you deserve it, you don't have to ask."
It's interesting because a single post can seem to gather both, causing you to wonder if you deserved either.

I'm kind of wondering about your tag. I seem remember seeing it years before transformers made it to the movies. Before that, they were silly/cool toys to me. Silly because I was an adult and above those things, cool because it reminded me of the toys I had as a kid and this was in reality, better than my imagination could make the ones I had.

Did you pick your name because of the transformer culture I never bothered to learn until I watched the movies?

I also applologize for how I handled this thread. My personal coding style is to treat the user as an adult, not some kid whose hand has to be slapped the second they slip on the keyboard. On the other hand, some apps make me regret they don't know about cntrl-Z. Some Nanny treatment by the programmer can be nice.

It's interesting because a single post can seem to gather both, causing you to wonder if you deserved either.

Indeed, it's a moving scale.

Did you pick your name because of the transformer culture I never bothered to learn until I watched the movies?

Not really, it was fairly random but no doubt I was thinking of the decepticons at the time. I added a misspelling to differentiate myself a bit.

I also want programmers to understand, when they get to keypress control, their responsibility on how their app acts, goes through the roof because you've disabled so many built in controls, you could render your app useless.

For instance, FORMS implements for you, mouseless screen navigation because it was possible to have a computer without a mouse. You should implement that yourself in any keypress event handler, at least let the cursor leave the control when either tab key is hit. Part of the reason I don't want to have keypress event handles, is because I don't want to learn how they are sent and what signal is received when sent.

Programmers disable things, sometimes without a clue on what they are disabling. Accepting things written without being fully thought out is something normally done by everyone.

Hopefully, people realize mouseless is possible because once someone hits one of those form fields, their only options when mouseless is to hold down the power key (not counted as a keyboard key) for a minute or bring up task manager (no personal clue how to do that without a mouse), pick the app you are on, and kill it, removing any benefit the app might have had.

their only options when mouseless is to hold down the power key (not counted as a keyboard key) for a minute or bring up task manager (no personal clue how to do that without a mouse),

Control-Shift-Escape

commented: ... without a mouse and trapped in a user control keypress validator that only allows numberics. +3

sorry fat-finger combined with fuzzy thoughts. ...numerics

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.