Search code examples
c#winformsevent-handlingtelerik

Only do event after complete


How to do the event handling when the user presses the ENTER key or leaves the focus on the particular textbox? I tried for KeyChanged event, but it will keep updating the number instead of only once when complete.

private void txtNumber_TextChanged(object sender, EventArgs e)
{
    txtNumber.Text = double.Parse(txtNumber.Text).ToString("F2");
}

Solution

  • There are a few issues with the posted code. One issue is that doing the formatting each time the user “types” a character is going to be awkward for the user. In addition, if the user presses the “Enter” key, the event txtNumber_TextChanged is not going to fire. I assume you may already know this.

    Next, when getting input from users, it is imperative that you check the input for valid numbers BEFORE calling the parse method…Example, the line of code…

    double.Parse(txtNumber.Text).ToString("F2");
    

    Will FAIL and crash the program if the text in the text box… txtNumber.Text is NOT a valid double.

    You should always assume the user is going to make a mistake and you don’t want your code to crash when they do.

    Therefore I suggest using the double.TryPasre method to avoid these possible crashes, calling this method will NEVER throw an exception and will make validating the number easier.

    To get what you want I recommend you wire up three (3) events for the text box…

    The Leave event, this is used to format the text, when the user leaves the text box, like when they click on another control.

    Next is the PreviewKeyDown event, this is used when the user presses the “Enter” key.

    And one extra event to help the user ONLY add numbers and one dot. The KeyPressed event is wired up and will ignore any pressed keys that are not numbers or the dot (period). Also, it will only allow one period, if the user tries to add a second decimal place, it will be ignored.

    Bear in mind, the key pressed event helps by preventing the user from “typing” alpha text into the text box… however, the user can still paste text. Fortunately, since we are using the TryParse method, when the pasted text is an invalid number, the try parse will simply return “0.00” and NOT crash the code.

    private void txtNumber_Leave(object sender, EventArgs e) {
      double.TryParse(txtNumber.Text.Trim(), out double number);
      txtNumber.Text = number.ToString("F2");
    }
    
    private void txtNumber_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
      if (e.KeyCode == Keys.Enter) {
        double.TryParse(txtNumber.Text.Trim(), out double number);
        txtNumber.Text = number.ToString("F2");
      }
    }
    
    private void txtNumber_KeyPress(object sender, KeyPressEventArgs e) {
      if (!char.IsControl(e.KeyChar) // <- key pressed is not a control key
        && !char.IsDigit(e.KeyChar)  // <- key pressed is not a digit (number)
        && e.KeyChar != '.') {       // <- key pressed is not a dot (.)
        e.Handled = true;            // <- if its not a control key, digit or dot... then ignore it
      }
      // only allow one decimal point - if there is already a dot, then ignore the second one
      if (e.KeyChar == '.' && txtNumber.Text.IndexOf('.') > -1) {
        e.Handled = true;            // <- if there is already a dot in the text... then ignore it
      }
    }