使用文本框在VB.Net中存储数字计数器

时间:2017-03-17 19:16:36

标签: vb.net

我想用TextBox计算。 这是我的代码:

Public Class Form1

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        OrainsProgressBar1.Increment(1)
        If OrainsProgressBar1.Value = 100 Then
            Timer3.Start()
            Timer1.Stop()
        End If
    End Sub

    Private Sub OrainsTheme1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OrainsTheme1.Click
    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Timer1.Start()
        Timer2.Start()
    End Sub

    Private Sub Timer3_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer3.Tick
        OrainsProgressBar1.Increment(-1)
        If OrainsProgressBar1.Value = 0 Then
            Timer1.Start()
            Timer3.Stop()
        End If
    End Sub

    Private Sub OrainsButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OrainsButton1.Click
        OrainsTextBox1.Text += 100
    End Sub

    Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
        OrainsTextBox1.Text += 1
    End Sub
End Class

但我在OrainsTextBox1.Text += 1时遇到错误。 VB说:

  

'从字符串转换""输入' Double'无效。'

有什么问题?

2 个答案:

答案 0 :(得分:1)

在.Net世界中,事物的数据类型非常重要。字符串(如.Text属性)是 NOT 数字。你需要转换。即使有人只在文本框中输入数字0-9,这仍然是数字字符字符串,而不是数字。如果有人将随机文本输入到根本不能转换为数字类型的文本框中会发生什么?

对于此代码,我建议构建一个属性,如下所示:

Private _orainsValue As Double
Public Property OrainsValue As Double
    Get
       Return _orainsValues
    End Get
    Set
         _orainsValue = Value
         OrainsTextBox1.Text = _orainsValue.ToString()
    End Set
End Property

这将允许您编写这样的代码并向用户显示预期结果:

Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
    OrainsVale += 1
End Sub

请注意,它确实意味着您将要禁用TextBox,因为这并不考虑用户数据输入。

答案 1 :(得分:0)

而不是像这样做OrainsTextBox1.Text + = 1

这样做OrainsTextBox1.Text = Val(OrainsTextBox1.Text)+ 1

因为.Text是字符串。将1s附加为“11111111”