TextBox input validation, numbers only - c#

Good day. I'm having a hard time with this. TextBox1 should only accept numbers and if the user input a text, a message box will pop-up saying that only numbers can be entered.
I don't know how to do this since the message box should pop-up without clicking any button.
The user will just really enter numbers and if they enter non numerical value the message box will appear instantly.
Is this even possible?
I've tried the KeyPress events but I can still input letters. Please help.

This is a very standard implementation, with a minor twist of including a dialog box. In general a dialog box is just going to annoy the user and take the focus away from the form, it breaks the flow of the user interaction so we try to avoid it, however you can adapt the standard example listed in the MS Docs - KeyEventHandler Delegate documentation:
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if(e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
//If shift key was pressed, it's not a number.
if (Control.ModifierKeys == Keys.Shift) {
nonNumberEntered = true;
}
}
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for the flag being set in the KeyDown event.
if (nonNumberEntered == true)
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true;
MessageBox.Show("Only numeric input is accepted");
}
}
Using the KeyEventArgs in this manner allows you access to the raw physical key that was pressed, and to separately prevent the textbox from accepting the key press.
This style of code is very useful when 3rd party controls (or your own code) has overriden the standard implementations. It is however possible to do it all in the KeyPress event handler:
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for the flag being set in the KeyDown event.
if (!Char.IsNumber(e.KeyChar) && e.KeyChar != '.')
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true;
MessageBox.Show("Only numeric input is accepted");
}
}
But that could still allow us to enter a value of "12.333...44..5" so a more complete example should extend one of the previous examples and compare against the current value in the textbox:
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for the flag being set in the KeyDown event.
bool isNumber = Char.IsNumber(e.KeyChar);
if (e.KeyChar == '.')
{
isNumber = !(sender as TextBox).Text.Contains(".");
}
if (!isNumber)
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true;
MessageBox.Show("Only numeric input is accepted");
}
}

Related

Are some keyboards more loquacious than others?

The lead developer says that when he uses my app, his keyboard beeps when he moves between TextBoxes on the TableLayoutPanel via the directional arrow keys.
However, I hear no such aural activity.
Here's my code:
// Had to intercept Up and Down arrows from Windows
private void textBoxPlatypi_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
TextBox tb = (TextBox)sender;
if (e.KeyCode.Equals(Keys.Up)) {
SetFocusOneRowUp(tb.Name);
return;
}
if (e.KeyCode.Equals(Keys.Down)) {
SetFocusOneRowDown(tb.Name);
return;
}
}
private void textBoxPlatypi_KeyDown(object sender, KeyEventArgs e) {
TextBox tb = (TextBox)sender;
if (e.KeyCode.Equals(Keys.Left)) {
SetFocusOneColumnBack(tb.Name);
e.Handled = true;
return;
}
if (e.KeyCode.Equals(Keys.Right)) {
SetFocusOneColumnForward(tb.Name);
e.Handled = true;
return;
}
}
..He thought maybe I needed "e.Handled" but that is not available in the PreviewKeyDown event.
Is there a way to suppress the beeping (which apparently occurs only with certain keyboards or specific setups (he's using Windows7, I'm on XP still))?
UPDATE
I've got this code now:
private void textBoxPlatypus1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
switch (e.KeyCode) {
case Keys.Down:
case Keys.Up:
e.IsInputKey = true;
break;
}
}
private void textBoxPlatypus1_KeyDown(object sender, KeyEventArgs e) {
TextBox tb = (TextBox)sender;
if (e.KeyCode.Equals(Keys.Up)) {
SetFocusOneRowUp(tb.Name);
e.Handled = true;
return;
}
if (e.KeyCode.Equals(Keys.Down)) {
SetFocusOneRowDown(tb.Name);
e.Handled = true;
return;
}
if (e.KeyCode.Equals(Keys.Left)) {
SetFocusOneColumnBack(tb.Name);
e.Handled = true;
return;
}
if (e.KeyCode.Equals(Keys.Right)) {
SetFocusOneColumnForward(tb.Name);
e.Handled = true;
return;
}
}
...but he still hears the beeping (I don't).
He's in Alaska and using Windows 7; I'm in California and using XP. I don't know if some combination/mismatch there is the problem...
UPDATED AGAIN
I know this may be shocking to some, but the Alaska/California disconnection has nothing to do with it. I'm now hearing the beeps, too, and it's not from the arrow keys. It's when a value is entered in a TextBox and then, if that text box already has a character, focus is moved to the next textBox and the value is entered there (this is my code that causes this to happen). But the irritating beeping seems to be random - I haven't figured out the pattern for when it beeps (sometimes it does, sometimes it doesn't)...has anybody ever run across anything like that, or, better yet, know how to suppress the beep? All I'm doing is pressing either the "1" or the "2" key above the keyboard.
There is no way in the PreviewKeyDownEvent to Handle / Supress a KeyEvent like there is in the normal KeyDown Event. What the documentation suggests is to set the PreviewKeyDownEventArgs.IsInputKey property to true in order to handle key presses that are not available normally in the KeyDown Event.
From above Link, they are using a button as an example:
Some key presses, such as the TAB, RETURN, ESC, and arrow keys, are typically ignored by some controls because they are not considered input key presses... By handling the PreviewKeyDown event for a Button and setting the IsInputKey property to true, you can raise the KeyDown event when the arrow keys are pressed. However, if you handle the arrow keys, the focus will no longer move to the previous or next control.
Try this:
e.SuppressKeyPress = true;

Stop the 'Ding' when pressing Enter

I have a very simple Windows Forms Application. And, in Windows (or, atleast Windows Forms Applications), when you press Enter while inside a Single-line TextBox Control, you hear a Ding. It's an unpleasent sound, that indicated you cannot enter a newline, because it is a single-line TextBox.
This is all fine. However, in my Form, I have 1 TextBox, and a Search Button. And I am allowing the user to Perform a search by pressing Enter after they've finished typing, so they don't have to use the mouse to click the Search Button.
But this Ding sound occurs. It's very annoying.
How can we make it so just that sound doesn't play at all in my Form?
#David H - Here's how I'm detecting the enter pressing:
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// Perform search now.
}
}
It works for me:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
//Se apertou o enter
if (e.KeyCode == Keys.Enter)
{
//enter key is down
this.doSomething();
e.Handled = true;
e.SuppressKeyPress = true;
}
}
The SuppressKeyPress is the really trick. I hope that help you.
Check out the Form.AcceptButton property. You can use it to specify a default button for a form, in this case for pressing enter.
From the docs:
This property enables you to designate
a default action to occur when the
user presses the ENTER key in your
application. The button assigned to
this property must be an
IButtonControl that is on the current
form or located within a container on
the current form.
There is also a CancelButton property for when the user presses escape.
Try
textBox.KeyPress += new KeyPressEventHandler(keypressed);
private void keypressed(Object o, KeyPressEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true; //this line will do the trick
}
}
Just add e.SuppressKeyPress = true; in your "if" statement.
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//If true, do not pass the key event to the underlying control.
e.SuppressKeyPress = true; //This will suppress the "ding" sound.*/
// Perform search now.
}
}
You can Use KeyPress instead of KeyUp or KeyDown its more efficient
and here's how to handle
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
button1.PerformClick();
}
}
and say peace to the 'Ding'
Use SuppressKeyPress to stop continued processing of the keystroke after handling it.
public class EntryForm: Form
{
public EntryForm()
{
}
private void EntryTextBox_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
e.Handled = true;
e.SuppressKeyPress = true;
// do some stuff
}
else if(e.KeyCode == Keys.Escape)
{
e.Handled = true;
e.SuppressKeyPress = true;
// do some stuff
}
}
private void EntryTextBox_KeyUp(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
// do some stuff
}
else if(e.KeyCode == Keys.Escape)
{
// do some stuff
}
}
}
On WinForms the Enter key causes a Ding sound because the form property AcceptButton is not specified.
If you don't need an AcceptButton the ding sound can be suppressed by setting the form KeyPreview to true and enter the following KeyPress event:
private void Form_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
e.Handled = true;
}
No matter what control is active, there will be no more ding sound when pressing the Enter key. Since the key event proccessing order is KeyDown, KeyPress and KeyUp the Enter key will still work for the KeyDown events for the controls.
I stumbled on this post while trying to handle a KeyDown this worked for me.
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
btnLogIn.PerformClick()
End If
Supressing the Key Press stops the event from being sent to the underlying control. This should work if you're manually handling everything that the enter key will be doing within that textbox. Sorry about the Visual Basic.
$("#txtSomething").keypress(function (e) {
if (e.which == 13) {
e.Handled = true; //This will prevent the "ding" sound
//Write the rest of your code
}
});
There is a very little chance anyone gets to this answer but some other answers are truly scary. Suppressing event on KeyDown kills 2 additional events in one strike. Setting e.Handled property to true is useless in this context.
The best way is to set Form.AcceptButton property to the actual Search Button.
There is also another way of utilizing Enter key - some people may want it to act as TAB button. To do that, add a new Button, set its Location property outside of the Form area (i.e. (-100, -100)) - setting Visible property to false may disable Button handlers in some cases. Set Form.AcceptButton property to your new button. In Click event handler add following code
this.SelectNextControl(ActiveControl, true, true, true, true)
Now, you may want to transfer focus only when focus it on TextBox you may want to either test ActiveControl type or use e.Supress property in event handlers of controls not meant to use Enter as TAB
That's it. You don't even need to capture e.KeyCode
Set your Search button's IsDefault property to true. This will make it a default button and it will be auto-clicked when Enter is pressed.
Well I lived with this problem long enough and looked it up here.
After thinking about this for quite some time and wanting the simplest way to fix it I came up with the easiest but not so elegant way to fix it.
Here is what I did.
Put 2 invisible buttons "Ok" and "Cancel" on the form.
Set the AcceptButton and CancelButton Property on the form to the invisible buttons.
Added no code to the buttons!
This solved all the secondary problems listed in this thread including the ToolStripMenu. My biggest complaint was the BindingNavigator, when I would enter a record number into the Current position to navigate to and pressed enter.
As per the original question in which the programmer wanted a search function when the enter button was pressed I simply put the search code in the invisible OK Button!
So far this seems to solve all problems but as we all know with Visual Studio, something will probably crop up.
The only other possible elegant way I could think of would be to write a new keystroke handling class which is way to much work for most of my projects.
You can set your textbox multi-line to true then handle the Enter key press.
private void yourForm_Load(object sender, EventArgs e)
{
textBox1.Multiline = true;
}
//then write your TextBox codes
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// doSomething();
}
}
i changed the textbox properties for an multiline textbox and it works for me.
Concerning the e.SuppressKeyPress = true; solution, it works fine by itself. Setting SuppressKeyPress to true also sets Handled to true, so there's no need to use e.Handled= true;
void RTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
//do ...
bool temp = Multiline;
Multiline = true;
e.Handled = true;
Multiline = temp;
}
}

How to make Textbox only accept alphabetic characters

I have a windows forms app with a maskedtextbox control that I want to only accept alphabetic values in.
Ideally, this would behave such that pressing any other keys than alphabetic keys would either produce no result or immediately provide the user with feedback about the invalid character.
This question has probably been asked and answered a million times on every conceivable programming forum. Every answer provided has the distinction of being unique to the stated requirements.
Since you are using a MaskedTextBox, you have additional validation features available to you and do not really need to handle keypresses. You can simply set the Mask property to something like "L" (character required) or "?" (optional characters). In order to show feedback to the user that the input is not acceptable, you can use the BeepOnError property or add a Tooltip to show the error message. This feedback mechanism should be implemented in the MaskedInputRejected event handler.
The MaskedTextBox control offers a ValidatingType property to check input that passes the requirements of the Mask, but may not be the correct datatype. The TypeValidationCompleted event is raised after this type validation and you can handle it to determine results.
If you still need to handle keypress events, then read on...!
The method I would recommend in your case is that instead of handling the KeyDown event (you ostensibly do not need advanced key handling capability) or using a Regex to match input (frankly, overkill), I would simply use the built-in properties of the Char structure.
private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
Char pressedKey = e.KeyChar;
if (Char.IsLetter(pressedKey) || Char.IsSeparator(pressedKey) || Char.IsPunctuation(pressedKey))
{
// Allow input.
e.Handled = false
}
else
// Stop the character from being entered into the control since not a letter, nor punctuation, nor a space.
e.Handled = true;
}
}
Note that this snippet allows you to handle punctutation and separator keys as well.
From MSDN (This code shows how to handle the KeyDown event to check for the character that is entered. In this example it is checking for only numerical input. You could modify it so that it would work for alphabetical input instead of numerical):
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if(e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
//If shift key was pressed, it's not a number.
if (Control.ModifierKeys == Keys.Shift) {
nonNumberEntered = true;
}
}
// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for the flag being set in the KeyDown event.
if (nonNumberEntered == true)
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true;
}
}
This code will distinguish alphabetic character key presses from non alphabetic ones:
private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Regex.IsMatch(e.KeyChar.ToString(), #"\p{L}"))
{
// this is a letter
}
else
{
// this is NOT a letter
}
}
Update: note that the above regex pattern will match ONLY alphabetic characters, so it will not allow spaces, commas, dots and so on. In order to allow more kinds of characters, you will need to add those to the pattern:
// allow alphabetic characters, dots, commas, semicolon, colon
// and whitespace characters
if (Regex.IsMatch(e.KeyChar.ToString(), #"[\p{L}\.,;:\s]"))
// This is to allow only numbers.
// This Event Trigger, When key press event occures ,and it only allows the Number and Controls.,
private void txtEmpExp_KeyPress(object sender, KeyPressEventArgs e)
{
if(Char.IsControl(e.KeyChar)!=true&&Char.IsNumber(e.KeyChar)==false)
{
e.Handled = true;
}
}
//At key press event it will allows only the Characters and Controls.
private void txtEmpLocation_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsControl(e.KeyChar) != true && Char.IsNumber(e.KeyChar) == true)
{
e.Handled = true;
}
}
//Add a text box select it & goto Events & In the event list double click on "keypress" event.
if (!char.IsLetter(e.KeyChar))
{
MessageBox.Show("Enter only characters");
}
}
This works for me :)
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !((e.KeyChar != 'ñ' && e.KeyChar != 'Ñ') && char.IsLetter(e.KeyChar));
}
Try this code
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space);
}

Validate on text change in TextBox

I have implemented validation rules on a textBox in my WinForm and it works well. However it checks the validation only when I tab out of the field. I would like it to check as soon as anything is entered in the box and everytime the content changes. Also I'd like it to check validation as soon as the WinForm opens.
I remember doing this fairly recently by setting some events and whatnot, but I can't seem to remember how.
If you're using databinding, go to the Properties of the textbox. Open (DataBindings) at the top, click on the (Advanced) property, three dots will appear (...) Click on those. The advanced data binding screen appears. For each property of the TextBox that is bound, in your case Text, you can set when the databinding, and thus the validation, should "kick in" using the combobox Data Source Update mode. If you set it to OnPropertyChanged, it will re-evaluate as you type (the default is OnValidation which only updates as you tab).
TextChanged event
in the future you can find all of the events on the MSDN library, here's the TextBox class reference:
http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox(VS.80).aspx
How will your data be valid if it isn't finished? i.e. a user types a number and you try and validate it as a date?
When binding your textbox to a bindingSource go to Advanced and select validation type
"On Property Changed". This will propagate your data to your entity on each key press.
Here is the screen shot
You should be checking on KeyPress or KeyDown events and not just your TextChanged event.
Here is a C# Example direct from the MSDN documentation:
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if(e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
//If shift key was pressed, it's not a number.
if (Control.ModifierKeys == Keys.Shift) {
nonNumberEntered = true;
}
}
// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for the flag being set in the KeyDown event.
if (nonNumberEntered == true)
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true;
}
}

Locking down valid characters in a Textbox

I need to be able to lock down the valid characters in a textbox, I presently have a regex which I can check each character against such as
[A-Za-z]
would lock down to just Alpha characters.
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back)
{
base.OnKeyPress(e);
return;
}
if (String.IsNullOrEmpty(this._ValidCharExpression))
{
base.OnKeyPress(e);
}
else
{
bool isValidChar = Regex.Match(e.KeyChar.ToString(),this._ValidCharExpression).Success;
if (isValidChar)
{
base.OnKeyPress(e);
}
else
{
e.Handled = true;
}
}
}
I had placed the regex code in the OnKeyPress code, but I wat to allow all special keys, such as Ctrl-V, Ctrl-C and Backspace to be allowed.
As you can see I have the backspace key being handled. However, Ctrl-V, for example cannot see the V key because it runs once for the ctrl key but does not see any modifiers keys.
What is the best way to handle this situation?
MaskedTextBox may be right for you.
You can also look at the FilterTextBox over at CodeProjct. You can use it (or the approach described) to do what you intend. The basic idea is to cancel the change before it is becoming visible (via an OnTextChanging event).
What if you put the validation in OnTextChanged instead of OnKeyPress, but each time it passes validation you save the value to a variable? Then you can revert if the user pastes or types an incorrect string, as well as give some other UI hint that something was invalid (e.g. set a Label's text).
Why don't you put the check for valid characters in the OnTextChanged event
and then deal with the Ctrl+C, Ctrl+V in the on key down
Also you can use the e.ModifierKeys == Keys.Control to test for control keys
http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.aspx
You can use one of the OnKeyPress / OnKeyUp / OkKeyDown events and then use the Char.IsLetter method to check that the entered key is a letter.
The solution that I have come up with is to check the keys in the OnKeyDown event and then setting a flag if the keypress should be handled, which is then check in the OnKeyPress event.
protected override void OnKeyDown(KeyEventArgs e)
{
Keys keyCode = (Keys)e.KeyValue;
base.OnKeyDown(e);
if ((e.Modifiers == Keys.Control) ||
(e.Modifiers == Keys.Control) ||
(keyCode == Keys.Back) ||
(keyCode == Keys.Delete))
{
this._handleKey = true;
}
else
{
// check if the key is valid and set the flag
this._handleKey = Regex.Match(key.ToString(), this._ValidCharExpression).Success;
}
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (this._handleKey)
{
base.OnKeyPress(e);
this._handleKey = false;
}
else
{
e.Handled = true;
}
}

Categories