开发者

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

开发者 https://www.devze.com 2023-01-16 23:13 出处:网络
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.

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

精彩评论

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