سؤال

So I have a Subtotal TextBox where an amount like $546.75 can be entered. Now, I want to make sure that only numbers, ONE decimal, One Dollar Symbol and commas allowed only every 3 places (100,000,000). Is this possible? Maybe not the commas, but at least the numbers, decimal, and dollar symbol.

هل كانت مفيدة؟

المحلول

I think you are using WinForms and not WPF. If that is the case then you could use System.Windows.Forms.ErrorProvider (you can drag-drop one from toolbox to your form) along with regular expressions to do the validation.

WARNING: The regex pattern string below may not do exactly you want but hopefully conveys the idea.

Some match examples... "$4,000.00", "-$4000.00", "-$400.00"

    private void textBox1_Validating(object sender, CancelEventArgs e)
    {
        string error = null;
        string pattern = @"^\$?\-?([1-9]{1}[0-9]{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\-?\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\(\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))\)$";

        if (!Regex.IsMatch(textBox1.Text, pattern))
        {
            error = "Please enter a US currency value.";
            e.Cancel = true;
        }
        errorProvider1.SetError((Control)sender, error);
    }

نصائح أخرى

Why you dont put the money sign "$" out side of the textBox (create a label just infrontof textBox), then you will not have to worry about this character, but only about numbers. And it looks better (in my opinion). Then you can use this code:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar != (Char)Keys.Back) //allow backspace (to delete)
        {
            e.Handled = !char.IsNumber(e.KeyChar);
        }
    }

All validation should be performed manually on KeyPress event.

Here described validation for numeric values values. You will need to check the '$' sign and decimals additionally.

//tb - is the name of text box

    private void tb_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        char[] inputChar = e.Text.ToCharArray();

        if (char.IsNumber(inputChar[0]))
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }

// another method.

        if (char.IsDigit(inputChar[0]))
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top