How to textbox validation for currency in c#

The code I have written here will be usefull to validate the currency format.
 That means It will not take '.' value at the start of the textbox. The textbox will allow only two digits after the '.' value and only allows numeric values. Try it for validating money and percentages.

     TextBox tbprice = sender as TextBox;

            if (e.KeyChar != (char)Keys.Back)
            {
                int dotIndex = tbprice.Text.IndexOf('.');
                if (char.IsDigit(e.KeyChar))
                {
                    if (dotIndex != -1 && dotIndex < tbprice.SelectionStart && tbprice.Text.Substring(dotIndex + 1).Length >= 2)
                    {
                        e.Handled = true;
                    }
                }
                else
                    e.Handled = e.KeyChar != '.' || dotIndex != -1 || tbprice.Text.Length == 0 || tbprice.SelectionStart + 2 < tbprice.Text.Length;
            }

I hope this code will help you.

1 comment: