lothos12345 Posted July 31, 2006 Posted July 31, 2006 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. Quote
Cags Posted July 31, 2006 Posted July 31, 2006 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...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 ClassThe 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 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. Quote Anybody looking for a graduate programmer (Midlands, England)?
mskeel Posted August 1, 2006 Posted August 1, 2006 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. Quote
mskeel Posted August 7, 2006 Posted August 7, 2006 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. Quote
Leaders snarfblam Posted August 7, 2006 Leaders Posted August 7, 2006 It is a VB6/VB8 control, magically missing from version 7 (.Net 1.x). Quote [sIGPIC]e[/sIGPIC]
mskeel Posted August 8, 2006 Posted August 8, 2006 Very odd. This one looks good for .Net 1.x -- http://www.codeproject.com/useritems/MaskedTextBox.asp Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.