Textbox

lothos12345

Junior Contributor
Joined
May 2, 2002
Messages
294
Location
Texas
Using visual basic I want to prevent the user from entering '*' into a textbox. How can this be done? Any help offered is greatly appreciated.
 
Often the simplest method is to allow the user to add the character, but using validation to not allow them to continue untill they have removed it. If this is not an option, you could inherit the textbox control overriding the onKeyPress method and thus prevent them from entering the value, like so...
Visual Basic:
Public Class ExtendedTextbox
    Inherits System.Windows.Forms.TextBox

    Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If e.KeyChar = "*" Then
            e.Handled = True
        End If
    End Sub
End Class
The biggest problem with this is that the user can still paste the character into the textbox. Another method (which will solve the paste problem) is to use the OnTextChange event and remove and stars which are present, like so
Visual Basic:
    Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)
        Text = Text.Replace("*", "")
    End Sub
Whilst this method should work I have no idea how efficient it would be if you are working with large strings.
 
Doing a blanket replace of *'s OnTextChanged is confusing if you aren't expecting it.

Look to web usability patterns for a better overall solution...

0. Tell the user what data format you expect in a label or something to preempt bad data.
1. Prevent the user from typing in bad data as Cags showed in the first code segment and warn them when they do something wrong so they know why their characters aren't showing up.
2. Always validate the data before you run with it and tell the user when something is wrong and what is wrong with it so they can repair it themselves.

It's all about educating the user not to enter *'s in the first place and then telling them to correct what they entered as soon as you are able.
 
Check out the masked text box control. At first I thought this was used for masking text (i.e. password field) but really it's for applying a mask to distinguish between good and bad input. I haven't played with it too much, but it looks like it will handle what you are looking to do. It might be a 2.0 only control, so hopefully that'll work for you.
 
Back
Top