我创建了一个文本框,输入联系人号码,并将其设置为maxlength = 11。如何防止用户输入小于11位数字?只有11位数字。坦克西斯
发布于 2019-11-17 07:18:39
一般来说,您应该在Validating事件处理程序中执行验证。如果数据验证失败,则取消事件,控件将不会失去焦点。您可以在使用数据之前调用ValidateChildren,以确保即使是从未接收到焦点的控件也会得到验证。
Private Sub TextBox1_Validating(sender As Object, e As CancelEventArgs) Handles TextBox1.Validating
If TextBox1.TextLength < TextBox1.MaxLength OrElse TextBox1.Text.Any(Function(ch) Not Char.IsDigit(ch)) Then
TextBox1.HideSelection = False
TextBox1.SelectAll()
MessageBox.Show($"Please enter an {TextBox1.MaxLength}-digit number",
"Invalid Input",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
TextBox1.HideSelection = True
e.Cancel = True
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ValidateChildren() Then
'All data is valid so it is safe to use it.
End If
End Sub发布于 2019-11-17 07:49:31
您可以考虑使用一个MaskedTextBox -它将允许您指定11位数字必须输入,它甚至可以有分隔字符,如连字符为电话号码。我链接到MSDN -看看
顺便提一句,如果用户输入了错误的MessageBox电话号码--消息框非常烦人,并且中断用户界面的流程,那么考虑不要使用/incomplete来给用户反馈。现在的方法是在输入字段旁边显示一些突出显示的警告,而不是显示一些停止用户输入的内容,必须将其排除在外,因为这会打断用户的思路。
发布于 2019-11-17 06:35:34
我已经想出了答案:
我在“属性设计”选项中将Txtbox.Contact设置为maxlength = 11。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Txtbox_Contact.TextLength = 11 Then
MessageBox.Show("Contact Number is Accepted")
Else
MessageBox.Show("Please input 11 digit number!")
End If
End Subhttps://stackoverflow.com/questions/58897921
复制相似问题