Development Experience

Thursday, May 3, 2012

numeric textbox c#

numeric textbox c# is very important issue if you deal with numbers in your program.
I was looking for a simple solution for numeric textbox c# . While I was looking for a solution I saw a very nice code in StackOverflow.
The code for numeric textbox was very nice but it has some problems.
You can use the event handler below for numeric textbox c#.
It doesn't allow multiple dots and number without decimal.


private void textBoxNumbersOnly_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox t = (TextBox)sender;

            if (e.KeyChar == '.' && t.Text.Length == 0)
            {
                e.Handled = true;
                return;
            }

            if (e.KeyChar=='.' && t.Text.Contains('.') == true)
            {
                e.Handled = true;
                return;
            }

            if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b' || e.KeyChar == '.')
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

No comments:

Post a Comment