2

Please see the screenshot below for a MaskedTextBox:

enter image description here

and the code below:

public Form1()
        {
            InitializeComponent();
            this.Load += Form1_Load;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            maskedTextBox1.ValidatingType = typeof(System.Decimal);
            maskedTextBox1.TypeValidationCompleted += new TypeValidationEventHandler(maskedTextBox1_TypeValidationCompleted);
        }

        void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e)
        {
            if (!e.IsValidInput)
            {
                MessageBox.Show("Validation failed");
            }
            else
            {
                Decimal value = (Decimal)e.ReturnValue;
                MessageBox.Show("Validation suceeded");
            }
        }
}

e.IsValidInput is always false if I enter a value less than 1000. If I enter a value above 1,000 then it works i.e. the cast to a decimal works. I believe this is because the comma is missing with values less than 1,000. How do I make the comma optional?

w0051977
  • 15,099
  • 32
  • 152
  • 329
  • 1
    You probably want `maskedTextBox1.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;` – LarsTech May 09 '17 at 17:24
  • @LarsTech using this Format if I enter 100.00 e.ReturnValue is becoming 10000 for some reason. – Samvel Petrosov May 09 '17 at 17:28
  • @S.Petrosov Divide by 100? MaskedTextBox is one of those controls that never works to everyone's satisfaction. I never used it in a production setting. – LarsTech May 09 '17 at 17:36
  • @LarsTech , is there a way just to exclude the comma i.e. keep the full stop. – w0051977 May 09 '17 at 17:56
  • @w0051977 I think there is no way and you will have to do it manually by writing code because the value that was input for example was 1,000.00 is stored as 100000, you can check it if handle Leave event or even in the TypeValidationCompleted event if you get value of the maskedTextBox.Text you will see it. – Samvel Petrosov May 09 '17 at 18:03

0 Answers0