如何检查大于零的文本框控件值?

时间:2016-08-04 15:05:14

标签: c# asp.net validation

我有总分的文本框。 我需要在具有读取值的其他文本框上禁用验证。

我需要检查的条件是总得分是否大于零且为空或为空。这是代码。我试图放置(!string.IsNullOrEmpty(txtTotalScore.Text))&& (txtTotalScore.Text>0) 它没有用,因为txtscore是文本框控件而0是整数。 我该如何解决这个问题?

TextBox myscore = fv.FindControl("txtTotalScore") as TextBox;
if (!string.IsNullOrEmpty(txtTotalScore.Text))                      
    RangeValidator rv = fv.FindControl("rngReading") as RangeValidator;
    rv.Enabled = false;
}

2 个答案:

答案 0 :(得分:1)

为了将TextBox的内容与整数进行比较,您需要将内容解析为数字(即“42”= 42)。您可以使用Parse()TryParse()方法,然后将结果与0进行比较。

if (!string.IsNullOrEmpty(txtTotalScore.Text))      
    // At this point, you know it isn't null
    var potentialValue = -1;
    // Parse the textbox and store the value in potentialValue
    Int32.TryParse(txtTotalScore.Text, out potentialValue);
    if(potentialValue > 0)
    {
          // Then disable your range validator
          RangeValidator rv = fv.FindControl("rngReading") as RangeValidator;
          rv.Enabled = false;
    }  
}

答案 1 :(得分:1)

我只是将文本框的文本转换为int,然后进行肯定检查:

TextBox myScore = fv.FindControl("txtTotalScore") as TextBox;
try
{
    int totalScore = Convert.ToInt32(myScore.Text);
    if (totalScore > 0)
    {
        RangeValidator rv = fv.FindControl("rngReading") as RangeValidator;
        rv.Enabled = false;
    }
}
catch(FormatException ex)
{
    // Show error message stating that text should be a numeric value
}