1

I've got a combo box that I want to allow users to enter in numerical digits, but not allow them to enter alphabetical characters.

My problem is that these numbers can be decimal so I need to allow the user to enter .

I've used char.IsSymbol but it doesn't seem to do what I want it to do.

private void DaySelection_ComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && !char.IsSymbol(e.KeyChar))
    {
        e.Handled = true;
    }
}
Thomton
  • 102
  • 13
  • 1
    Does this answer your question? [How do I make a textbox that only accepts numbers?](https://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers) – madmonk46 Oct 19 '22 at 10:56
  • @madmonk46 it does under the surface but my question isn't just about accepting only numbers which is the confusion I had with the title of that question – Thomton Oct 19 '22 at 11:03

2 Answers2

1

Your best bet might be to have a specific list of allowed characters, and check against that. You can use a string for this for ease:

static readonly string _allowedNumericCharacters = "-0123456789.";

private void DaySelection_ComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!_allowedNumericCharacters.Contains(e.KeyChar))
    {
        e.Handled = true;
    }
}

Do you need the thousands separator? If so, you'll need to add , to the string.

Note that you might need to adjust that string for different locales. The decimal mark and the thousands separator is different for different locales.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
1

You could also use regex to do this, just something simple like

^[0-9.-]*$ 

This will just allow you to input any character between 0 and 9, a dot or a hyphen, then you just need to check if your string matches this. This should give the same result as the above answer.

Also I believe its better to test the whole string rather than an individual character upon a key press, this just adds extra protection for stuff like if they copy/paste text into the form

JDChris100
  • 146
  • 9