2014-02-24 61 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

右對對錯!多謝你們!我不知道我錯過了它!謝謝! –