neel
neel

Reputation: 5303

Validate number INTEGER on text boxes IN windows forms issue

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.

Upvotes: 3

Views: 3516

Answers (2)

Mehbube Arman
Mehbube Arman

Reputation: 490

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

Upvotes: 5

Kishore Anumala
Kishore Anumala

Reputation: 1

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

Upvotes: 0

Related Questions