views:

63

answers:

2

I'm making a little app for calculating tips for Windows Phone 7 and I want to validate the inputs before trying to calculate things.

How can I check if the textbox has a valid monetary value inserted? No letters and no more than one Dot for decimal places.

+1  A: 

The criteria you describe could be checked with a RegEx but it would make more sense to just check with decimal.TryParse()

string txt = MyTextBox.Text;
decimal value;

if (decimal.TryParse(txt, 
        NumberStyles.AllowDecimalPoint, 
        CultureInfo.InvariantCulture, out value))
{
    // got it
}

The NumberStyles and CultureInfo (IFormatprovider) are up for discussion.

Henk Holterman
They are. The comma is right next to the smiley: http://www.intomobile.com/2010/09/14/windows-phone-keyboard/
Hans Passant
A: 

Use TextChanged event of your textBox and show the result in another one

  private void PriceTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {

        float price;
        if (float.TryParse(priceTextBox.Text, out price))
        {
            tipTextBox.Text = calculate().ToString();
        }
        else
        {
            tipTextBox.Text = "wrong";
        }
   }

EDIT: use Culture info if needed

lukas