文本框只能接受 00 - 60 之间的整数
Textbox that can only accept integer ranging from 00 - 60
我想通过不接受除 00 到 60 之间的整数以外的任何内容来验证用户在文本框中的输入。
条件:
- 如果用户输入 0 或什么都不输入,系统应该将其视为 00(注意我用 0 填充了它。
- 我知道我也可以在
numericupdown
中执行此操作,但由于某些原因我不能使用它。
- 我需要在 20 个文本框中应用它。
这是代码,实际上它正在运行。我唯一的问题是我不能将它应用到 20 个文本框,它只在 tb_hour_1 文本框中工作,有什么我可以做的而不是在这行代码 Dim num As Integer = Integer.Parse(String.Format("{0}{1}", If(Tb_Hour_1.Text = String.Empty, "", Tb_Hour_1.Text), e.KeyChar.ToString()))
中指示 tb_hour_1.text
].
代码:
Private Sub Tb_Hour_1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Tb_Minute_2.KeyPress, Tb_Minute_1.KeyPress,
Tb_Hour_2.KeyPress, Tb_Hour_1.KeyPress
Dim Min_Num As Integer = 0
Dim Max_Num As Integer = 60
If e.KeyChar <> ControlChars.Back Then
'allow backspace for deleting
e.Handled = Not Char.IsNumber(e.KeyChar)
'allow numbers only
If Not e.Handled Then
Dim num As Integer = Integer.Parse(String.Format("{0}{1}", If(Tb_Hour_1.Text = String.Empty, "", Tb_Hour_1.Text), e.KeyChar.ToString()))
If num < Min_Num OrElse num > Max_Num Then
e.Handled = True
End If
End If
End If
End Sub
您最好为此创建一个 UserControl。它验证输入和范围,而不是创建 20 个文本框,然后您可以使用自定义控件。此外,MaskedTextBox
控件也可用于避免检查文本长度,它也只能允许数字。
此外,一个快捷方式可能是像这样列出所有剩余控件的事件:
Private Sub Tb_Hour_1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Tb_Minute_2.KeyPress, Tb_Minute_1.KeyPress,
Tb_Hour_2.KeyPress, Tb_Hour_1.KeyPress, ....... further control events
对所有文本框使用通用事件处理程序是可以的。只需将 Tb_Hour_1 替换为演员表即可,即:
Ctype(sender,TextBox)
我想通过不接受除 00 到 60 之间的整数以外的任何内容来验证用户在文本框中的输入。
条件:
- 如果用户输入 0 或什么都不输入,系统应该将其视为 00(注意我用 0 填充了它。
- 我知道我也可以在
numericupdown
中执行此操作,但由于某些原因我不能使用它。 - 我需要在 20 个文本框中应用它。
这是代码,实际上它正在运行。我唯一的问题是我不能将它应用到 20 个文本框,它只在 tb_hour_1 文本框中工作,有什么我可以做的而不是在这行代码 Dim num As Integer = Integer.Parse(String.Format("{0}{1}", If(Tb_Hour_1.Text = String.Empty, "", Tb_Hour_1.Text), e.KeyChar.ToString()))
中指示 tb_hour_1.text
].
代码:
Private Sub Tb_Hour_1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Tb_Minute_2.KeyPress, Tb_Minute_1.KeyPress,
Tb_Hour_2.KeyPress, Tb_Hour_1.KeyPress
Dim Min_Num As Integer = 0
Dim Max_Num As Integer = 60
If e.KeyChar <> ControlChars.Back Then
'allow backspace for deleting
e.Handled = Not Char.IsNumber(e.KeyChar)
'allow numbers only
If Not e.Handled Then
Dim num As Integer = Integer.Parse(String.Format("{0}{1}", If(Tb_Hour_1.Text = String.Empty, "", Tb_Hour_1.Text), e.KeyChar.ToString()))
If num < Min_Num OrElse num > Max_Num Then
e.Handled = True
End If
End If
End If
End Sub
您最好为此创建一个 UserControl。它验证输入和范围,而不是创建 20 个文本框,然后您可以使用自定义控件。此外,MaskedTextBox
控件也可用于避免检查文本长度,它也只能允许数字。
此外,一个快捷方式可能是像这样列出所有剩余控件的事件:
Private Sub Tb_Hour_1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Tb_Minute_2.KeyPress, Tb_Minute_1.KeyPress,
Tb_Hour_2.KeyPress, Tb_Hour_1.KeyPress, ....... further control events
对所有文本框使用通用事件处理程序是可以的。只需将 Tb_Hour_1 替换为演员表即可,即:
Ctype(sender,TextBox)