Friday, June 14, 2013

Allow only numbers and decimal in a textbox

This piece of code will allow users to enter only numbers and one decimal point (.) in a textbox
private void txtMCurReading_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsControl(e.KeyChar))
            {
                //
            }
            else if (char.IsLetter(e.KeyChar))
            {
                e.Handled = true;
            }
            else if (Char.IsNumber(e.KeyChar) || e.KeyChar == '.')
            {
                TextBox tb = sender as TextBox;
                int cursorPosLeft = tb.SelectionStart;
                int cursorPosRight = tb.SelectionStart + tb.SelectionLength;
                string result = tb.Text.Substring(0, cursorPosLeft) + e.KeyChar + tb.Text.Substring(cursorPosRight);
                string[] parts = result.Split('.');
                if (parts.Length > 1)
                {
                    if (parts[1].Length > 2 || parts.Length > 2) // change here for setting number of chars after decimal

                    {
                        e.Handled = true;
                    }
                }
                if (parts[0].Length > 10) // change here for setting number of chars before decimal
                {
                    e.Handled = true;
                }
            }
            else if (!Char.IsNumber(e.KeyChar))
            {
                e.Handled = true;
            }

        }

No comments: