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;
}
}
CodePudding user response:
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.
CodePudding user response:
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