[英]Input Numbers and Unit Grades Only at Textbox (VB.Net)
Hi I Just Want to Input 1 to 5 only as unit grades on textbox i use this code: 嗨,我只是想输入1到5作为文本框上的单位成绩,我使用以下代码:
Private Sub TextBox16_TextChanged(sender As Object, e As EventArgs) Handles TextBox16.TextChanged
If TextBox16.Text >= 5 Then
TextBox16.clear()
MsgBox("Unit Grades Only From 1 to 5")
End If
End Sub
End Class 结束班
error came up: 错误出现:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll Microsoft.VisualBasic.dll中发生了未处理的“System.InvalidCastException”类型异常
Additional information: Conversion from string "" to type 'Double' is not valid. 附加信息:从字符串“”到类型“ Double”的转换无效。
If you have your heart set on using a textbox for this , the following code should prevent any besides a 1 through 5 in the textbox. 如果您打算为此使用文本框,则以下代码应防止在文本框中使用1到5之外的任何内容。 I used a textbox with a bit better naming txtUnitGrade. 我使用的文本框命名为txtUnitGrade更好。
Private _sLastValidValue As String = String.Empty
Private _bIgnoreChange As Boolean = False
Private Sub txtUnitGrade_TextChanged(sender As Object, e As EventArgs) Handles txtUnitGrade.TextChanged
If Not _bIgnoreChange Then
If txtUnitGrade.Text = String.Empty Then
_sLastValidValue = String.Empty
Else
If Not IsNumeric(txtUnitGrade.Text) Then
SetValueToLast()
Else
Dim iParsedValue As Integer = Integer.MinValue
If Not (Integer.TryParse(txtUnitGrade.Text, iParsedValue)) OrElse iParsedValue < 0 OrElse iParsedValue > 5 Then
SetValueToLast()
Else
_sLastValidValue = txtUnitGrade.Text
End If
End If
End If
End If
End Sub
Private Sub SetValueToLast()
Beep() 'you could add some other audible or visual cue that an block occured
_bIgnoreChange = True
txtUnitGrade.Text = _sLastValidValue
txtUnitGrade.SelectionStart = txtUnitGrade.Text.Length
_bIgnoreChange = False
End Sub
Alright you have two ways to do this: 好了,您有两种方法可以做到这一点:
Preventing Typing Them 防止输入
In this case, you will deny user from typing other characters. 在这种情况下,您将拒绝用户键入其他字符。 So code this: 因此编写此代码:
Private Sub TextBox16_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox16.KeyPress
'Deny user from entering more than one charecter
TextBox1.MaxLength = 1
Select Case e.KeyChar
Case "1", "2", "3", "4", "5" ,vbBack 'vbBack is backspace
'You can enter any number that you whant
e.Handled = False
Case Else
'Ignore the key
e.Handled = True
'Play a Beep sound.
Beep()
End Select
End Sub
or 要么
Checking With TextChanged 用TextChanged检查
Type in this in your method: 在您的方法中输入:
Dim textbox_val As Integer
'The user may enter alphabetical characters
Try
textbox_val = Convert.ToInt32(TextBox1.Text)
Catch ex As Exception
MsgBox("Unit Grades Only From 1 to 5")
Exit Sub
End Try
If textbox_val >= 5 Then
TextBox1.Clear()
MsgBox("Unit Grades Only From 1 to 5")
End If
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.