curiousDev
curiousDev

Reputation: 437

KeyDown event with user input validation

in the following code, I am trying to get only decimal value. but the textfield input comes as different strings. Need to validate against numbers and backspace,delete key

if ((e.KeyValue >= 48 && e.KeyValue <= 57) || (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) && (textBox1.Text.Length < textBox1.MaxLength))
{
    if (e.KeyCode != Keys.Delete && e.KeyCode != Keys.Back)
    {
        if (e.KeyValue >= 48 && e.KeyValue <= 57)
        {
            enteredNumber = e.KeyData.ToString();
        }
        else
        {
            enteredNumber = e.KeyData.ToString().Substring(0, 1);
        }
    }
    textBox1.Text = textBox1.Text + enteredNumber;
}

if i enter 1 in the text box , iam getting its ascii value 149 in the text box since its appending 49 - ascii value of 1 in the text box.Can you suggest how to fix this?

Upvotes: 2

Views: 1345

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

Please state your problem clear. Supposing, that you want to restrict user's input in order to let user input digits only ('0'..'9') you can do something like that:

  private void myTextbox_KeyPress(object sender, KeyPressEventArgs e) {
    if (Char.IsDigit(e.KeyChar))
      return;
    else if (e.KeyChar < ' ') // <- I suggest that you allow user to press ESC, TAB etc.
      return;

    // Other keys are forbidden
    e.Handled = true;
  }

P.S. Remember, however, that user can paste something incorrect, in order to prevent that you can use TextChanged event:

private void myTextbox_TextChanged(object sender, EventArgs e) {
  if (!Regex.IsMatch(myTextbox.Text, @"^\d*$")) {
    // User's trying to PASTE something wrong from the Clipboard
    // Let's, for instance, remove his/her input in that case:
    myTextbox.Text = "";
  }
}

Upvotes: 3

Related Questions