I am developing WP7 application. I am new to the WP7. I am also new to the silverlight. I have a textbox in my application. In this textbox user enters the amount. I want to give the facility in my application so that user can enter the float amount ( for e.g. 1000.50 or 499.9999). The user should be able to enter either two digit or four digit after the '.' .My code for the textbox is as follows.
<TextBox InputScope="Number" Height="68" HorizontalAlignment="Left" Margin="-12,0,0,141" Name="AmountTextBox" Text="" VerticalAlignment="Bottom" Width="187" LostFocus="AmountTextBox_LostFocus" BorderBrush="Gray" MaxLength="10"/>
I have done the following validations for the above textbox.
public void AmountTextBox_LostFocus(object sender, RoutedEventArgs e)
{
foreach (char c in AmountTextBox.Text)
{
if (!char.IsDigit(c))
{
MessageBox.Show("Only numeric values are allowed");
AmountTextBox.Focus();
return;
}
}
}
How to resolve the above issue. Can you please provide me any code or link through which I can resolve the above issue. If I am doing anything wrong then please guide me.
The following code is working fine for me. I have tested it in my application. In the following code by adding some validations we can treat our general textbox as a numeric textbox which can accept the float values.
public void AmountTextBox_LostFocus(object sender, RoutedEventArgs e)
{
foreach (char c in AmountTextBox.Text)
{
if (!char.IsDigit(c) && !(c == '.'))
{
if (c == '-')
{
MessageBox.Show("Only positive values are allowed");
AmountTextBox.Focus();
return;
}
MessageBox.Show("Only numeric values are allowed");
AmountTextBox.Focus();
return;
}
}
string [] AmountArr = AmountTextBox.Text.Split('.');
if (AmountArr.Count() > 2)
{
MessageBox.Show("Only one decimal point are allowed");
AmountTextBox.Focus();
return;
}
if (AmountArr.Count() > 1)
{
int Digits = AmountArr[1].Count();
if (Digits > 2)
{
MessageBox.Show("Only two digits are allowed after decimal point");
AmountTextBox.Focus();
return;
}
}
}