在 vb.net 中验证文本框 [英] validate a textbox in vb.net

查看:47
本文介绍了在 vb.net 中验证文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何验证 vb.net 中的文本框,以便在我输入字母以外的任何内容时显示错误消息

How could i validate a textbox in vb.net, so that it gives error message if i enter anything apart from alphabets

推荐答案

您可以检查文本字符串,即 textbox1.text,以确保它在 .Leave 事件中除了字母字符之外没有任何内容.例如,当用户切换到下一个控件时,这将捕获错误.您可以使用正则表达式执行此操作(在此示例中导入 System.Text.RegularExpressions),或者您可以手动"检查文本.

You can check the text string, i.e., textbox1.text, to make sure it has nothing besides alphabet characters in the .Leave event. This will catch an error when the user tabs to the next control, for example. You can do this using a regular expression (import System.Text.RegularExpressions for this example), or you can check the text "manually."

Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave
  If Not Regex.Match(TextBox1.Text, "^[a-z]*$", RegexOptions.IgnoreCase).Success Then
    MsgBox("Please enter alpha text only.")
    TextBox1.Focus()
  End If
End Sub

如果您想在用户按下非 alpha 键时立即停止,您可以使用 TextChanged 事件而不是 .Leave 事件.

If you want to stop the user as soon as a non-alpha key is pressed, you can use the TextChanged event instead of the .Leave event.

这篇关于在 vb.net 中验证文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆