I\'m looking to accept digits and the decimal point, but no sign.
I\'ve looked at samples using the NumericUpDown control for Windows Forms, and this sample of a Num
Now I know this question has an accepted answer, but personally, I find it a bit confusing and I believe it should be easier than that. So I'll try to demonstrate how I got it to work as best as I can:
In Windows Forms, there's an event called KeyPress
which is perfectly good for this kind of task. But that doesn't exist in WPF, so instead, we'll be using the PreviewTextInput
event. Also, for the validation, I believe one can use a foreach
to loop through the textbox.Text
and check if it matches ;) the condition, but honestly, this is what regular expressions are for.
One more thing before we dive into the holy code. For the event to be fired, one can do two things:
Loaded
event of the form (which the textBox is in):
textBox.PreviewTextInput += onlyNumeric;
I think the second method is better because in situations like this, you'll mostly be required to apply the same condition (regex
) to more than one TextBox
and you don't want to repeat yourself!.
Finally, here's how you'd do it:
private void onlyNumeric(object sender, TextCompositionEventArgs e)
{
string onlyNumeric = @"^([0-9]+(.[0-9]+)?)$";
Regex regex = new Regex(onlyNumeric);
e.Handled = !regex.IsMatch(e.Text);
}