Link to home
Start Free TrialLog in
Avatar of bertino12
bertino12

asked on

Making a textbox only accept numbers and commas

I want to make a textbox only accept numbers and commas. What is the best way to do this?
Avatar of kaufmed
kaufmed
Flag of United States of America image

You could implement a custom TextBox by inheriting the original and adding some custom code (or just use the custom KeyPress code on your existing box).
class NumberTextBox : System.Windows.Forms.TextBox
{
    private readonly List<char> valids = new List<char>() { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',' };
 
    public NumberTextBox() : base()
    {
        this.KeyPress += new KeyPressEventHandler(NumberTextBox_KeyPress);
    }
 
    void NumberTextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!valids.Contains(e.KeyChar))
        {
            e.Handled = true;
        }
    }
}

Open in new window

void NumberTextBox_KeyPress() should be implemented as below. Sorry, I posted incorrect code for that.
void NumberTextBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    if (!valids.Contains(e.KeyChar))
    {
        e.Handled = true;
    }
}

Open in new window

If you want backspace to be allowed, then change the char list to the following:
private readonly List<char> valids = new List<char>() { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '\b' };

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bertino12
bertino12

ASKER

I get the error:
'Contains' is not a member of 'System.Array'.      
Okay, Just had to change  valids()  to an arraylist so i could use the contains method. Thanks. It seems to be working just fine.