3

i have textbox on a windows form and i want to be insert only numbers in this textbox.i use the following c# code for that

private void ChildAge_TextChanged(object sender, EventArgs e)
{
    int i;
    if (!int.TryParse(ChildAge.Text, out i))
    {
        MessageBox.Show("Plaese enter a valid Age");
    }    
}

it is working, but the problem is that , after showing the Message, when i Backspace the content and text box become null, on that situation also this message box shows again.

5
  • I assume you mean that ChildAge.Text becomes null? Not the actual ChildAge? Commented Mar 14, 2014 at 9:19
  • yes. first time no problem , only when click backspace and all content remove from text box again this msgbox shows Commented Mar 14, 2014 at 9:22
  • 2
    Do a test like this if(!string.isNullEmpty(ChildAge.Text)) { if (!int.TryParse(ChildAge.Text, out i)) { MessageBox.Show("Plaese enter a valid Age"); } } Commented Mar 14, 2014 at 9:23
  • 2
    erm, (!string.IsNullOrWhitespace(ChildAge.Text) && !int.TryParse(ChildAge.Text, out i)) Commented Mar 14, 2014 at 9:25
  • 4
    or instead override OnKeyPress and cancel any presses that don't pass char.IsDigit. Commented Mar 14, 2014 at 9:27

2 Answers 2

5

Do a little test like bellow:

int i = 0;
if(!string.IsNullOrEmpty(ChildAge.Text) && 
     !int.TryParse(ChildAge.Text, out i)
  )
{
    MessageBox.Show("Enter Valid Age");
}
Sign up to request clarification or add additional context in comments.

1 Comment

could use && to save indentation
0

Try Using Below. This works better.

  bool m_BackPressed = false;
    private void ChildAge_TextChanged(object sender, EventArgs e)
    {
        int i;
        if (!m_BackPressed)            
        {
            if (!int.TryParse(ChildAge.Text, out i))
            {
                MessageBox.Show("Plaese enter a valid Age");
            } 
        }


    }

    private void ChildAge_KeyPress(object sender, KeyPressEventArgs e)
    {

        m_BackPressed = (e.KeyChar.Equals((char)Keys.Back)) ? true : false;
    }

1 Comment

yes. But what if user enters multiple characters and then start pressing backspace to delete all characters in textbox?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.