如何在VB.Net 2010中创建一个只接受30到250之间数字的TextBox。我需要将值存储在Integer中,以便我可以在计算中使用它。
Dim x As String = textbox1
Dim y As Integer
y = Cint(textbox1)
If x <= 29 then
Msg("cant accept")
Textbox1 = ""
End if
答案 0 :(得分:6)
验证Validating
事件处理程序中控件的内容,如果失败则取消该事件。如果控件包含无效文本,则会阻止控件失去焦点。然后,您可以稍后使用CInt
或Convert.ToInt32
确认内容。
Private Sub TextBox1_Validating(sender As Object, e As CancelEventArgs) Handles TextBox1.Validating
Dim number As Integer
If Not Integer.TryParse(TextBox1.Text, number) OrElse
number < 30 OrElse
number > 250 Then
MessageBox.Show("Please enter an integer from 30 to 250.",
"Invalid Input",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
'Don't let the control lose focus.
e.Cancel = True
End If
End Sub
答案 1 :(得分:0)
我建议您使用NumericUpDown控件而不是TextBox,但如果您想使用TextBox,请尝试以下操作:
Private Sub TextBox1_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.Leave
Dim int As Integer = 0
If Not Integer.TryParse(TextBox1.Text, int) Then
MessageBox.Show("You should enter a number")
TextBox1.Clear()
Return
End If
If int < 30 OrElse int > 150 Then
MessageBox.Show("You should enter a number between 30 and 150")
TextBox1.Clear()
End If
End Sub