开发者

How to validate that a textbox has a valid monetary value inputed?

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 m开发者_C百科onetary value inserted? No letters and no more than one Dot for decimal places.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜