int.TryParse()始终返回true

时间:2014-02-24 20:46:10

标签: c# .net int tryparse

我的程序包含一个文本框。 我需要检查它是否只有数字,然后打印。

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

问题是,由于某种原因,它总是返回true,然后转到

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

为什么会这样?

2 个答案:

答案 0 :(得分:1)

2个变化:

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

答案 1 :(得分:0)

您可能想检查TextBox的值而不是Label。因此,this.TextBox.Text代替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");
}