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
精彩评论