Skip to main content
 首页 » 编程设计

c#之VB 如何检查文本框中的负值

2024年02月13日21xiaohuochai

我们如何检查文本框中的负值?我只能对文本框进行 TryParse 验证,以便验证它是否为数值:

If Not Decimal.TryParse(txtParts.Text, decParts) Then 
    If decParts <= 0 Then 
        MessageBox.Show("ERROR: Value must be a positive number!") 
    End If 
    MessageBox.Show("ERROR: Value must be numeric!") 
    Return False 
End If 

是否可以在 TryParse 方法中检查负值?

请您参考如下方法:

您的 If 条件基本上是说它是否没有成功地将其解析为数字。你想要这样的东西:

If Decimal.TryParse(txtParts.Text, decParts) Then 
    If decParts <= 0 Then 
        MessageBox.Show("ERROR: Value must be a positive number!") 
        Return False 
    End If 
Else 
    MessageBox.Show("ERROR: Value must be numeric!") 
    Return False 
End If 

注意 Else 子句,Decimal.TryParse 的条件反转,以及“not positive”部分的 return 语句。