views:

4751

answers:

3

I'm looking to accept digits and the decimal point, but no sign.

I've looked at samples using the NumericUpDown control for WinForms, and this sample of a NumericUpDown custom control from Microsoft. But so far it seems like NumericUpDown (supported by WPF or not) is not going to provide the functionality that I want. The way my app is designed, nobody in their right mind is going to want to mess with the arrows. They don't make any practical sense, in the context of my app.

So I'm looking for a simple way to make a standard WPF TextBox accept only the characters that I want. Is this possible? Is it practical?

Thanks, SO!

+2  A: 

Add in a VALIDATION RULE that when the text changes checks to determine if the data is numeric, and if it is, allows processing to continue, and if it is not, prompts the user that only numeric data is accepted in that field.

Read more here: http://www.codeproject.com/KB/WPF/wpfvalidation.aspx

Stephen Wrighton
+6  A: 

Add a preview text input event. Like so: <TextBox PreviewTextInput="PreviewTextInput" />.

Then inside that set the e.Handled if the text isn't allowed. e.Handled = !IsTextAllowed(e.Text);

I use a simple regex in IsTextAllowed to see if I should allow what they've typed. In my case I only want to allow numbers, dots and dashes.

private static bool IsTextAllowed(string text)
{
    Regex regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
    return !regex.IsMatch(text);
}

If you want to prevent pasting of incorrect data hook up the DataObject.Pasting event DataObject.Pasting="TextBoxPasting" as shown here

Ray
A: 

I need to allow only Decimal(6,2). So max number i could allow is 9999.99 How do i create a RegEx for this one.

I have got this Regex NumEx = new Regex(@"^\d+(?:.\d{0,2})?$"); however, it allows any number of integers before the decimal.

Thanks in advance.

Tushar

Tushar