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
Here I have a simple solution inspired by Ray's answer. This should be sufficient to identify any form of number.
This solution can also be easily modified if you want only positive numbers, integer values or values accurate to a maximum number of decimal places, etc.
As suggested in Ray's answer, you need to first add a PreviewTextInput
event:
Then put the following in the code behind:
private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
var textBox = sender as TextBox;
// Use SelectionStart property to find the caret position.
// Insert the previewed text into the existing text in the textbox.
var fullText = textBox.Text.Insert(textBox.SelectionStart, e.Text);
double val;
// If parsing is successful, set Handled to false
e.Handled = !double.TryParse(fullText, out val);
}
To invalid whitespace, we can add NumberStyles:
using System.Globalization;
private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
var textBox = sender as TextBox;
// Use SelectionStart property to find the caret position.
// Insert the previewed text into the existing text in the textbox.
var fullText = textBox.Text.Insert(textBox.SelectionStart, e.Text);
double val;
// If parsing is successful, set Handled to false
e.Handled = !double.TryParse(fullText,
NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign,
CultureInfo.InvariantCulture,
out val);
}