2013-04-10 103 views
1

我写了下面的代码:计数空白文本框为0值,而文本框为空

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

+0

是的,你可以解决你的问题。开始在VS选项中设置OPTION STRICT ON。 – Steve 2013-04-10 13:26:59

+0

不是VB6标签... – Rob 2013-04-10 13:32:38

+0

@Rob我将来会小心的。 – 2013-04-10 13:39:02

回答

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() 

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

+0

非常感谢你亲爱的。它运作良好。 – 2013-04-10 13:40:27

+0

我按照保罗的程序解决了我以前的问题。 (http://stackoverflow.com/a/15910866/2262815)。我想解决我自己的代码。希望你能做到。 – 2013-04-10 13:42:45