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

오른쪽 오른쪽 오른쪽! 고마워! 나는 그것을 어떻게 놓쳤는 지 몰랐다! 고맙습니다! –