Click here to Skip to main content
15,903,388 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,

may i request for help

How to restrict a user to enter only character values in a text box using VB.net code.



Cheers

Srikar
Posted

What i got you want to prevent the user to enter any numbers inside the textbox , am i right ?
If yes
You didn't mention you want to do this on windows or web application

for windows application you can inherit the texbox class to a new one for example called CustomTextbox
override the the keydown event (to prevent it while the user is entering )
or override the textchanged (to validate the text after the user enter the text ) , it's up to you to choose the write event. In the first case Ex:
public class CustomTextbox : TextBox
   {
       protected override void OnKeyDown(KeyEventArgs e)
       {
           base.OnKeyDown(e);
           //write your own logic here
       }
   }

Inside the e you will find too much data to validate the new character entered by the user and you can escape it if it's not valid

this will help you later on to make this textbox multi function control throw adding some new properties like the validation type (numeric or characters only)

So hope that i could help , happy programming
 
Share this answer
 
In case of Web I think you might use javascript to handle this :

function validateNumericOnKeyPress(e) {
        var evt = e || window.event;
        var key = evt.keyCode || evt.which;
        var src = evt.srcElement;

        if ((key >= 48 && key <= 57) || key == 8 || key == null)
            return true;
        else if (src.value.indexOf(".") == -1 && key == 46)
            return true;
        else
            return false;
}


Place this inside a script block on head section.

now in the txtbox use
<br />
txtbox.Attributes.Add("onkeypress", "javascript:return validateNumericOnKeyPress(event)")


For windows, I think the answer is already mentioned. Just added to that you need to track keypress event on the textbox and use
e.Handled = True /False ...

when e.Handled = True the character will not appear in the textbox.

Hope this help you. :thumbsup:
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900