RE: Validation of Textbox on a Windows form C#

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Would the NumericUpDown control work for you? It has all the functionality built in to ensure that only numbers are entered as well as allowing you to set the increment value, min value and max value. Nice little control for numeric only entry.
 
Thanks it is a nice control I did not see it there it almost worked but I could not see if there was a way to turn off the updown arrow.??

The number I will be using in the text box is a 8 digit Bank ID like 77777770
and I dont want the user to be able to enter any alpha characters.
 
The easiest way I know to do this is to keep users from entering nonnumeric data to begin with. Try this:

Declare a form level boolean:
private bool nonNumPressed = false;

Capture the KeyDown event for the editbox and add this code:
private void OnKeyDown(object sender, KeyEventArgs e)
{
// Initialize the flag to false.
nonNumPressed = false;

// see if the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// see if the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// see if 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.
nonNumPressed = true;
}
}
}
}

Capture the KeyPress event and enter this code:
private void OnKeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumPressed == true)
{
// stop the non-numeric character from being entered into the textbox.
e.Handled = true;
}
}

Now there is nothing to validate because you know that only numbers were entered. Now set the MaxLength property to 8 and you're good to go.

You could easily create your own numeric textbox control by inheriting from the TextBox control and adding this code. Drop it in your toolbox and it will be ready to go whenever you needed it.
 
Back
Top