将空白文本框计为0值时文本框为空

时间:2013-04-10 13:24:31

标签: vb.net

我写了以下代码:

Dim i As Integer
Dim pos As Integer = 0
Dim neg As Integer = 0
Dim zer As Integer = 0
Dim TextBoxes() As String = {Val(TextBox1.Text), Val(TextBox2.Text),
                              Val(TextBox3.Text), Val(TextBox4.Text),
                              Val(TextBox5.Text), Val(TextBox6.Text),
                              Val(TextBox7.Text), Val(TextBox8.Text),
                              Val(TextBox9.Text), Val(TextBox10.Text)}
For i = 0 To 9
    If TextBoxes(i) > 0 Then
        pos += 1
    End If
    If TextBoxes(i) < 0 Then
        neg += 1
    End If
    If TextBoxes(i) = 0 Then
        zer += 1
    End If
Next i
Label4.Text = (pos)
Label5.Text = (neg)
Label6.Text = (zer)

当程序执行并且我在文本框中放入了一些值时,输出看起来像this。第一个文本框包含1,其为正数,另一个包含-1,为负数。它运作良好。

此处出现问题:程序将空框计为0并在零总数中显示8。所有其他8个文本框都留空。如何解决问题,使其不将空文本框计为0

供参考,以下是我之前已解决的相关问题:Finding String of Substring in VB without using library function

1 个答案:

答案 0 :(得分:1)

问题是您正在调用Val函数来获取每个文本框中的值。如果给定文本为空或非数字,则Val会返回0。如果要检查它,您应该只将原始字符串存储在数组中,然后检查循环中的值,如下所示:

Dim i As Integer
Dim pos As Integer = 0
Dim neg As Integer = 0
Dim zer As Integer = 0
Dim TextBoxes() As String = {TextBox1.Text, TextBox2.Text,
                              TextBox3.Text, TextBox4.Text,
                              TextBox5.Text, TextBox6.Text,
                              TextBox7.Text, TextBox8.Text,
                              TextBox9.Text, TextBox10.Text}
For i = 0 To 9
    If TextBoxes(i) <> String.Empty Then
        If Val(TextBoxes(i)) > 0 Then
            pos += 1
        End If
        If Val(TextBoxes(i)) < 0 Then
            neg += 1
        End If
        If Val(TextBoxes(i)) = 0 Then
            zer += 1
        End If
    End If
Next i
Label4.Text = pos.ToString()
Label5.Text = neg.ToString()
Label6.Text = zer.ToString()

但是,Val函数主要是为了向后兼容VB6而提供的。它会起作用,但我建议改用Integer.TryParse。请注意,我还在最后三行添加了ToString。正如其他人所提到的那样,你应该转向Option Strict On

相关问题