如何将 Val 函数与“"进行比较在 Vb.Net [英] How to compare Val function with "" in Vb.Net
问题描述
我让用户输入一个文本框,然后按如下方式验证它:
I am taking a user input a text box and then Validating it as follows:
Val(txt_score1.text)
然后我必须将它与该文本框中的空白条目进行比较.像这样:
Then I have to compare it with blank entry in that text box. Like this:
If (Val(txt_score1.Text) = "") Then....
我收到一个转换错误.因为 "" 是 String 而 Val 返回的是 Integer.
I am receiving a conversion error. Because "" is String whereas Val is returning Integer.
如何克服这个问题??
推荐答案
您可以使用 Integer.TryParse 以确定该值是否为正确的整数:
You can use Integer.TryParse to determine if the value is a proper integer:
Dim x As Integer
If Integer.TryParse(TextBox1.Text, x) Then
MessageBox.Show(x)
Else
MessageBox.Show("'" + TextBox1.Text + "' is not a valid number")
End If
如果你只需要检查一个空字符串,你可以使用 String.IsNullOrEmpty 在文本本身上:
If you need to just check for a blank string, you can use String.IsNullOrEmpty on the text itself:
If String.IsNullOrEmpty(TextBox1.Text) Then
MessageBox.Show("String is empty")
End If
Val
是 VB6 时代遗留下来的遗留函数,如果你不知道它会有一些奇怪的行为.由于这个原因,我避免使用它.例如,采用以下案例及其生成的输出:
Val
is a legacy function leftover from VB6 days and has some weird behavior if you don't know about it. I avoid it for this reason. For example, take the following cases and the output they generate:
MessageBox.Show(Val("")) '0
MessageBox.Show(Val("5")) '5
MessageBox.Show(Val("5e3")) '5000
MessageBox.Show(Val("5xyz")) '5
这篇关于如何将 Val 函数与“"进行比较在 Vb.Net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!