Question

My program contains a textbox. I need to check if it gets only numbers, then print.

        int num;
        if (this.Tree.GetType() == Main.TestInt.GetType())
        {
            if (int.TryParse(this.label.Text,out num) == true) // i tried without the == before
            {
                this.Tree.SetInfo(int.Parse(this.TextBox.Text));
                base.label.Text = base.TextBox.Text;
            }
            else
            {
                base.TextBox.Text = "";
                MessageBox.Show("Only Numbers Allowed", "Error");
            }
        }

The problem is, for some reason it always returns true, and goes to the

    this.Tree.SetInfo(int.Parse(this.TextBox.Text));

Why is it happening?

Was it helpful?

Solution

2 changes:

    int num;
    if (this.Tree.GetType() == Main.TestInt.GetType())
    {
        if (int.TryParse(this.TextBox.Text,out num)) //1,  you were parsing label.Text
        {
            this.Tree.SetInfo(num); //2, don't bother parsing it twice!
            base.label.Text = base.TextBox.Text;
        }
        else
        {
            base.TextBox.Text = "";
            MessageBox.Show("Only Numbers Allowed", "Error");
        }
    }

OTHER TIPS

Probably you want to check the value of TextBox not the Label. So it would be this.TextBox.Text instead of this.Label.Text

if (int.TryParse(this.TextBox.Text,out num))
{
  this.Tree.SetInfo(this.TextBox.Text);
  base.label.Text = base.TextBox.Text;
}
else
{
  base.TextBox.Text = string.Empty;
  MessageBox.Show("Only Numbers Allowed", "Error");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top