10-03-2010, 09:53 PM
Hello guys, today I will be showing you a tutorial on how to restrict textbox input, which is very useful for many things such as numeric only textboxes, textboxes for your email with the @ sign, much much more. You may not know now, but when you need it for future reference your going to be saying "Thank L3g1tWa5te!" in your head... LOL... Now for the code and procedure.
Steps:
1) Enter the following code on the top of the form.
2) Now for TextBox1_TextChanged event code:
Your done. Now your textbox allows every kind of character thats not in the string "charactersDisallowed", as you can tell numbers are the only type of input allowed.
Now to make it so the textbox can only have certain characters, so the only characters that are allowed are in the string.
1) Now the same thing as before, enter the following code on the top/beginning of the form.
2) Now for TextBox2_TextChanged event code:
Thats it. Now the TextBox only allows the characters in the string, everything else is blocked for the text boxes' input.
Steps:
1) Enter the following code on the top of the form.
Code:
Public Class Form1
Dim charactersDisallowed As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,<>./?; :'{}[]=+-_)(*&^%$#@!~`|\uç▲ìα▲╜KÄ╤ZlÆn╘"
2) Now for TextBox1_TextChanged event code:
Code:
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
For x As Integer = 0 To TextBox1.Text.Length - 1
Letter = TextBox1.Text.Substring(x, 1)
If charactersDisallowed.Contains(Letter) Then
theText = theText.Replace(Letter, String.Empty)
End If
Next
TextBox1.Text = theText
TextBox1.Select(TextBox1.Text.Length, 0)
End Sub
Your done. Now your textbox allows every kind of character thats not in the string "charactersDisallowed", as you can tell numbers are the only type of input allowed.
Now to make it so the textbox can only have certain characters, so the only characters that are allowed are in the string.
1) Now the same thing as before, enter the following code on the top/beginning of the form.
Code:
Public Class Form1
Dim charactersAllowed As String = " abcdefghijklmnopqrstuvwxyz1234567890"
2) Now for TextBox2_TextChanged event code:
Code:
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
Dim CurrentText As String = TextBox2.Text
Dim Input As String
Dim SelectionIndex As Integer = TextBox2.SelectionStart
Dim Adjust As Integer
For x As Integer = 0 To TextBox2.Text.Length - 1
Input = TextBox2.Text.Substring(x, 1)
If charactersAllowed.Contains(Input) = False Then
CurrentText = CurrentText.Replace(Input, String.Empty)
Adjust = 1
End If
Next
TextBox2.Text = CurrentText
TextBox2.Select(SelectionIndex - Adjust, 0)
End Sub
Thats it. Now the TextBox only allows the characters in the string, everything else is blocked for the text boxes' input.