【发布时间】:2018-05-01 23:46:18
【问题描述】:
我正在尝试创建一个程序,该程序允许用户输入开始和结束值并选择数据类型。如果输入与数据类型范围匹配,程序将从开始值计数到结束值和时间,完成后程序将显示所用时间。
我在尝试只允许数字输入、十进制输入和负值时遇到了一些困难。我目前有:
Private Sub txtInputStart_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtInputStart.KeyPress
If Not IsNumeric(e.KeyChar) AndAlso System.Convert.ToByte(e.KeyChar) <> 8 AndAlso Convert.ToByte(e.KeyChar) <> 45 AndAlso System.Convert.ToByte(e.KeyChar) <> 46 Then
textError.Text = "Please enter numbers, decimals or negative values only"
e.Handled = True
End If
End Sub
Private Sub txtInputFinish_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtInputFinish.KeyPress
If Not IsNumeric(e.KeyChar) AndAlso System.Convert.ToByte(e.KeyChar) <> 8 AndAlso Convert.ToByte(e.KeyChar) <> 45 AndAlso System.Convert.ToByte(e.KeyChar) <> 46 Then
textError.Text = "Please enter numbers, decimals or negative values only"
e.Handled = True
End If
End Sub
我在实现双精度数据类型和十进制数据类型时也遇到了一些麻烦,我不确定如何检查输入是否适合这些数据类型。我目前的数据类型测试是这样的:
Select Case (cbDataType.SelectedIndex)
Case 0 'Byte'
If (lcValueStart < 0 Or lcValueFinish > 255) Then
textError.Text = "The selected data type Byte can only hold values from 0 through to 255, please reset the form and than try again"
Else
Do Until lcValueStart = lcValueFinish
lcValueStart = lcValueStart + 1
Loop
myTimer.Stop()
timeValue = (myTimer.Elapsed.ToString)
lblTimer.Text = timeValue
MessageBox.Show("Counting success")
textInfo.Text = "The data type Byte holds values from 0 up to 255 and can be assigned by: Dim varName As Byte = x"
End If
Case 1 'UShort'
If (lcValueStart < 0 Or lcValueFinish > 65535) Then
textError.Text = "The selected data type UShort can only hold values from 0 through to 65535, please reset the form and than try again"
Else
myTimer.Stop()
timeValue = (myTimer.Elapsed.ToString)
lblTimer.Text = timeValue
MessageBox.Show("Counting success")
textInfo.Text = "The data type UShort holds values from 0 up to 65535 and can be assigned by: Dim varName As UShort = x"
End If
这些数据类型很容易,因为它们不采用小数。有人可以在这里帮忙吗?
【问题讨论】:
-
为什么要让用户负担与数据类型有关的任何事情?有很多新手程序员不完全理解它们 (
orderNum = CStr(txtOrder.Text)) 另外,查看 NumericUpDown 并阅读 How to Ask 并获取 tour -
这是一个评估
-
不要试图完全限制。允许多个否定和句点字符,并让转换例程处理它。看起来您的输入过滤器应该工作得很好。它出什么问题了?虽然,实际上没有必要在不可接受的按键上显示错误。
-
缺少一堆代码。您如何从字符串转换为所需的数据类型?我会使用其中一个 Parse() 例程,例如 double.TryParse()。另外,请参阅数字类型的 MinValue 和 MaxValue 属性,而不是文字值(例如 65535)。
-
lcValueStart 和 lcValueFinish 设置为用户从文本框中输入的内容。该代码有效。如果他们选择了双精度数据类型或十进制数据类型,我只是对如何检查他们的输入值感到困惑。
标签: .net vb.net winforms visual-studio