C# 如何检查文本框是否没有值

C# 如何检查文本框是否没有值,c#,visual-studio,C#,Visual Studio,我有一个用户界面,其中有一个文本框(smartTextBox5),我必须在其中引入一个值。如果值大于1,应用程序应该执行一些操作,如果值小于1,应用程序应该执行其他操作 这是我的代码: double nInterval; nInterval = double.Parse(smartTextBox5.Value); if (nInterval > 1) { //do something } else { //do something else } 如果我引入一些值,它可以正常工

我有一个用户界面,其中有一个文本框(
smartTextBox5
),我必须在其中引入一个值。如果值大于1,应用程序应该执行一些操作,如果值小于1,应用程序应该执行其他操作

这是我的代码:

double nInterval;

nInterval = double.Parse(smartTextBox5.Value);

if (nInterval > 1)
{
 //do something

}
else 
{
 //do something else
}
如果我引入一些值,它可以正常工作,但是如果我让文本框没有任何值,或者如果我在文本框中只引入一个负号(
-
),它就会崩溃


有什么想法吗?

检查字符串是否为有效数字:

double nInterval;
if (Double.TryParse(smartTextBox5.Value, out nInterval)
{
    if (nInterval > 1)
    {
     //do something

    }
    else 
    {
     //do something else
    }
}

检查字符串是否为有效数字:

double nInterval;
if (Double.TryParse(smartTextBox5.Value, out nInterval)
{
    if (nInterval > 1)
    {
     //do something

    }
    else 
    {
     //do something else
    }
}

您的值必须是数字?您可以根据需要使用任何类型(int、double、long等)

int value;
if (int.TryParse(smartTextBox5.Value, out value) && 1 < value) {
     // Valid number.
} else {
     // Invalid number.
}
int值;
if(int.TryParse(smartTextBox5.Value,out值)和&1<值){
//有效号码。
}否则{
//无效号码。
}

您的值必须是数字?您可以根据需要使用任何类型(int、double、long等)

int value;
if (int.TryParse(smartTextBox5.Value, out value) && 1 < value) {
     // Valid number.
} else {
     // Invalid number.
}
int值;
if(int.TryParse(smartTextBox5.Value,out值)和&1<值){
//有效号码。
}否则{
//无效号码。
}

您可以使用
Double.TryParse()
,如果转换成功,此方法将返回
True
,如果转换不成功,则返回
False
。在您的情况下,如果文本框的值为空或像“-”这样的无效字符,它将返回
False

有关更多信息,请参阅

if (Double.TryParse(smartTextBox5.Value, out nInterval))
{
   if(nInterval > 1)
      .
      .
      .
}

您可以使用
Double.TryParse()
,如果转换成功,此方法将返回
True
,如果转换不成功,则返回
False
。在您的情况下,如果文本框的值为空或像“-”这样的无效字符,它将返回
False

有关更多信息,请参阅

if (Double.TryParse(smartTextBox5.Value, out nInterval))
{
   if(nInterval > 1)
      .
      .
      .
}

如果需要检查字符串值,请使用string.IsNullOrWhitespace()。为了避免这里出现异常,可以使用double.TryParse()方法。总之。。如果需要检查该值是否为有效的double,请使用TryParse方法。如果需要检查textbox是否包含任何文本,请在smartTxtBox.Value属性上使用string.IsNullOrWhiteSpace()。double.TryParse()将返回false,即使您得到一些无法转换为double的文本。如果需要检查字符串值,请使用string.IsNullOrWhitespace()。为了避免这里出现异常,可以使用double.TryParse()方法。总之。。如果需要检查该值是否为有效的double,请使用TryParse方法。如果需要检查textbox是否包含任何文本,请在smartTxtBox.Value属性上使用string.IsNullOrWhiteSpace()。double.TryParse()将返回false,即使您得到一些无法转换为double的文本。我怀疑是否有更好的方法。我错了,我更喜欢@Dovydas Sopa的版本来减少嵌套。这两个答案没有给出相同的结果,想法是一样的,但行为是不同的。我怀疑有更好的方法来做到这一点。我错了,我更喜欢@Dovydas Sopa的版本来减少嵌套。这两个答案给出的结果不同,想法相同,但行为不同