2014-02-24 65 views
-2

我的程序包含一个文本框。 我需要检查它是否只有数字,然后打印。int.TryParse()allways返回true

 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

你在你的'TryParse'语句解析'label.Text',不'TextBox.Text'。 – 48klocs

+2

您可以通过使用调试器轻松找到此类错误。尝试一下。 – usr

回答

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

右对对错!多谢你们!我不知道我错过了它!谢谢! –