C# int.TryParse()始终返回true
我的程序包含一个文本框。 我需要检查它是否只有数字,然后打印C# int.TryParse()始终返回true,c#,.net,int,tryparse,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.Tr
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变化:
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");
}
}
您可能想检查
文本框的值,而不是标签的值。所以它应该是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");
}
您正在分析tlyparse
语句中的label.Text
,而不是TextBox.Text
。通过使用调试器,您可以轻松找到此类错误。试试看,没错!谢谢大家!我不知道我怎么会错过它!非常感谢。