vb.net中的验证码
问题描述:
你好
i想要vb.net2010中文本框的验证码
只是我想接受这个字符并且不接受间距
hello
i want validation code for textbox in vb.net2010
just i want to accept the character and no accepting for spacing
答
有很多方法可以做到这一点。
1)你可以处理文本框的keydown / keypress事件。
2)您可以使用蒙版/自定义文本框(例如 - VB.NET TextBox验证控件 [ ^ ] )。
There are a number of ways to do this.
1) You could handle the keydown / keypress events of the textbox.
2) You could use a masked / custom text box (example - VB.NET TextBox Validation Control[^]).
试试这个:
Try this:
void CharacterValidation(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= 65 && e.KeyChar <= 90) || (e.KeyChar >= 97 && e.KeyChar <= 122) || e.KeyChar == 32 || e.KeyChar == 8)
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
这是另一个:
Here's another one:
Public Class MainForm
Dim charactersAllowed As String = " abcdefghijklmnopqrstuvwxyz"
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Dim theText As String = TextBox1.Text
Dim Letter As String
Dim SelectionIndex As Integer = TextBox1.SelectionStart
Dim Change As Integer
For x As Integer = 0 To TextBox1.Text.Length - 1
Letter = TextBox1.Text.Substring(x, 1)
If charactersAllowed.Contains(Letter) = False Then
theText = theText.Replace(Letter, String.Empty)
Change = 1
End If
Next
TextBox1.Text = theText
TextBox1.Select(SelectionIndex - Change, 0)
End Sub
End Class
Private Sub txtName_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtItemCode.KeyPress
If Asc(e.KeyChar) = Keys.Space Then
MessageBox.Show("Space not acceptable")
Exit Sub
Else
MessageBox.Show("GOOD")
End If
End Sub