Textbox for price/cash/currency on C#

前端 未结 6 550
慢半拍i
慢半拍i 2020-12-15 15:10

I have a problem that is haunting me for a while. I tried some solutions but they didn\'t worked.

I have a textbox that is for cash input ($999,99 for example). Howe

6条回答
  •  情话喂你
    2020-12-15 15:21

    Just a slight modification to GreatNates answer.

    private bool KeyEnteredIsValid(string key)
    {
      Regex regex;
      regex = new Regex("[^0-9]+$"); //regex that matches disallowed text
      return regex.IsMatch(key);
    }
    

    and insert this method into the textboxs preview input event like this.

    private void TextBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
      e.Handled = KeyEnteredIsValid(e.Text);
    }
    

    That way you make sure that you can't make any mistakes when typing anything. You are limited to numbers only with my methods, while nates methods are formatting your string.

    Cheers.

提交回复
热议问题