Jarrod Dall Jarrod Dall - 3 months ago 34
C# Question

C#, Textbox validation so that the numeric value format is three digits and one decimal

I have two questions:


  1. How to modify my code to validate the input numeric value is exactly three digits and one decimal place (see code below)

  2. Is this validation better to be placed in KeyPress event as it is now or should the validation be in button1 click event after all text boxes have been filled in?

    private void tbGRS1A_KeyPress(object sender, KeyPressEventArgs e)
    {
    // allow numeric values only
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
    (e.KeyChar != '.'))
    {
    e.Handled = true;
    }

    // only allow one decimal place
    if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
    {
    e.Handled = true;
    }



Also need to include error message...

Answer

I would do the validation using the event aptly named Validating.

A way to validate the input would be:

double value;
var trimmedInput = txtBox.Text.Trim(); //Not sure if you want this, if ' 231.3' or '231.3 ' is not valid remove it

if (trimmedInput.Length != 5 ||
    trimmedInput.IndexOf('.') != 3 ||
    !double.TryParse(trimmedInput, out value)
{
    //Input is not valid.
    //Set e.Cancel = true and set the corresponding text in the form's error provider
    //you could also simply clear the text box and have the user try again, etc.
}