-2

How can I allow only backspace and digits on a textbox ?

I've tried several solutions but none worked or they half-worked:

My code so far:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    try
    {
        if (textBox1.Text != String.Empty)
            textBox1.Clear();
        else
            value = Convert.ToInt32(textBox1.Text);//store the value from the textbox in variable "value"
    }
    catch (Exception e1)
    {
        MessageBox.Show(e1.Message);
    }
}

I would like a solution which is limitted only to private void textBox1_TextChanged()

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Cajuu'
  • 1,154
  • 2
  • 19
  • 50
  • 2
    if you enter else block texBox1.text will be string.empty. What the point to convert to int??? – apomene Mar 06 '15 at 13:45
  • I would like to omitt `private void textBox1_KeyPress()`. I've tried that and it doesn't work – Cajuu' Mar 06 '15 at 13:46
  • I need that value to be an integer so I can use it later – Cajuu' Mar 06 '15 at 13:46
  • @Dylan all answers in [that Q&A](http://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers) are horrible, both in implementation and UX. There is no protection against pasting in any of the answers, many of the suggestions are clearing the entire textbox when one invalid character is entered, there is no internationalization, KeyPress handling prevents navigation (arrow keys, Home/End, Backspace) ... the answer is "Use a MaskedTextBox". – CodeCaster Mar 06 '15 at 13:47
  • I do not think that this is a duplicate as I don't want that implementation :) – Cajuu' Mar 06 '15 at 13:49
  • @CodeCaster `MaskedTextBox` is [among the answers](http://stackoverflow.com/a/463324/238902). This question is still formulated similar to that one. – default Mar 06 '15 at 13:52
  • @Default sure, but that isn't the one with 341 upvotes. The highest upvoted answer allows pasting of invalid characters. I'm not saying it's not a duplicate, I'm saying we maybe need a better canonical answer for this issue. I may have wanted to say "almost all" in that comment though. – CodeCaster Mar 06 '15 at 13:53
  • The problem is that even though I used one of the solutions written there, I'm still getting an error message after `MessageBox.Show(aChar + " is not numeric");` is printed out. The same error message is printed if I am trying to delete some digits form the textbox(the error shows off at the last deleted digit). The error message says: `Unhandled exception has occured in your application...System.FormatException: Input string was not in a correct format.` – Cajuu' Mar 06 '15 at 13:59

1 Answers1

1

It looks like MaskedTextBox having Mask = "99900000" (as many 0 and 9 as you need digits, 0 is mandatory digit, 9 is optional) is good solution for you.

UPDATE

Probably, it was not clear from original answer - but if you're using MaskedTextBox - then you don't need to made some special checks in textBox1_TextChanged event handler since all the checks will be done by MaskedTextBox itself and your mask will ensure text contains only digits.

So your logic can be simplified to

private void textBox1_TextChanged(object sender, System.EventArgs e)
{
    int value;

    if (String.IsNullOrEmpty(textBox1.Text))
        value = 0; // modify it according to your logic - what should be if textbox is empty
    else    
        value = Convert.ToInt32(textBox1.Text);
}
Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
  • I would like another solution that fit my needs. This is marked as duplicate but in that link it doesn't exist an answer involving `backspace` key. Or either something to handle my error. (see the upper comments) – Cajuu' Mar 06 '15 at 14:18
  • I'm not sure if I've got your point. How `backspace` is related to the textbox content? Normal behaviour of backspace - is just erase last symbol in textbox. Why do you want to handle it somehow else? Or by `backspace` you means something not-usual? – Andrey Korneyev Mar 06 '15 at 14:22
  • I mean: if I enter some numbers in that textbox and let's say I typed them wrong and I am pressing backspace to delete them, I am getting a message box with an error. I don't know how to handle this. Any snippet related to my code would be really appreciated – Cajuu' Mar 06 '15 at 14:27
  • I made it work.Thanks, @Andy. I have one more question though: when I insert a letter it appears that error message again (which is good because user is not allowed to enter letters). Instead of that error I would like to add my own message. – Cajuu' Mar 06 '15 at 14:52
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/72415/discussion-between-alexander-and-andy-korneyev). – Cajuu' Mar 06 '15 at 15:03