Check for Spaces and Hyphens in the text Box VB.Net

farooque
farooque used Ask the Experts™
on
Hi There,

Can someone please let me know how do I prevent users from entering spaces and hyphens in the Textbox in VB.net

The Code that I am using does not work

 Private Sub txtLongSku_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtLongSku.KeyDown
        If e.KeyCode = Keys.Space Then
            e.Handled = True
             End If
        MessageBox.Show(e.KeyCode.ToString)
    End Sub
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
try
If e.KeyCode = Keys.Space OrElse e.KeyCode = Keys.Apps Then
Else
     e.Handled = True
End If

Open in new window

Commented:
Actually, use the KeyPress event and do:
Private Sub txtLongSku_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtLongSku.KeyPress
    If AscW(e.KeyChar) = 45 OrElse AscW(e.KeyChar) = AscW(Keys.Space) Then
        e.Handled = False
    Else
        e.Handled = True
    End If
End Sub

Open in new window

Commented:
Howdy!

There's also the option of creating your own custom textbox class by inheriting the Textbox class and then overiding the OnKeyPress event.


Public Partial Class CustomTextBox
	Inherits TextBox
	Protected Overrides Sub OnKeyPress(e As KeyPressEventArgs)
		If e.KeyChar = " "C OrElse e.KeyChar = "-"C Then
			e.Handled = True
		End If
	End Sub
End Class

Open in new window


Do that and you can just drop your custom textbox where ever you don't want someone entering a space or hyphen.

Nepaluz's solution is totally correct as well, this is just a different approach is all.

Cheers!
TwynFeyr
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

rtayIT Director

Commented:
you can use Regular Expressions also.

\w{5,255}  Does not allow spaces or special characters.


        Private Sub txtLongKu_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtLongSku.TextChanged
        Dim txtRegEx As New Regex("\w{5,255}")

        If txtRegEx.IsMatch(txtLongSku.Text) Then
            ErrorProvider1.SetError(txtLongSku, "")

        ElseIf txtRegEx.Text = "" Then
            ErrorProvider1.SetError(txtLongSku, "Required Field")

        Else
            ErrorProvider1.SetError(txtLongSku, "Spaces and Hyphens not allowed")

        End If
        Me.Validate()
    End Sub

You need to add an Error Provider to your form from the tool box.  Default name is ErrorProvider1.

The above example has a required field, that can be removed.
Top Expert 2015

Commented:
When you want to catch characters, you are better to use KeyPress than KeyDown or KeyUp.

The constant names given for the KeyCode in KeyDown and KeyUp works for an English US keyboard. But keys can be mapped differently on other types of keyboard. This does not only depends on the language, but also on the region. For instance, if you get KeyCode = Keys.Q on a French keyboard in France, the letter that was typed is a Z, not a Q. In Quebec, we use a different French keyboard whose mapping in closer to the English so we get the Q. But we have the same problem in other places. The KeyCode that generates / in the US gives up é on my keyboard mapping.

KeyPress is thus better for the situation discussed here, because it identifies the character that is sent to the screen, not the numeric code of the key.

KeyDown and KeyUp should be reserved for keys that do not generate a character, an by the same way do not generate a KeyPress, such as the function keys, Del and a few others.

So the accepted solution is not the best one. The best one should be the second one provided by nepaluz, but with the syntax provided by TwynFeyr. Why call a function (AscW) and make the code less readable, when e.KeyChar is already a value that you can evaluate against, and with code that does not requires you to remember the ASCII tables to understand.

However, TwynFeyr solution is a little farfetched. Using inheritance for a control that seems to be aimed at a specific use is a little too much.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial