Tuesday, 2 August 2016

Winform Textbox allow decimal number upto 2 decimal places C#


Use below code in the Keypress Event

private void txtPaidCcy_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsNumber(e.KeyChar) || e.KeyChar == '.')
            {
                int len = txtPaidCcy.Text.Length;
                bool hasDot = txtPaidCcy.Text.Contains(".");
                if (hasDot && e.KeyChar == '.')
                {
                    e.Handled = true;
                }
                if (len >= 20 && !hasDot)
                {
                    if (char.IsNumber(e.KeyChar))
                    {
                        e.Handled = true;
                    }

                }
                if (Regex.IsMatch(txtPaidCcy.Text, "^\\d*\\.\\d{2}$")) e.Handled = true;
            }
            else e.Handled = e.KeyChar != (char)Keys.Back;
        }



Virus-free. www.avast.com

No comments:

Post a Comment