KPath001
KPath001

Reputation: 870

Decimal Point in Windows phone textfield

Hello Fellow C# and Windows phone developers,

For my windows phone application, I have a textfield requiring the user to enter their age. During debugging mode I entered the number .8. and clicked proceed and the application unexpectedly closed. What code do I need to add so I can post a message box informing the user that numbers with more than 1 decimal point is unacceptable. Please Help

Upvotes: 2

Views: 490

Answers (2)

LZH
LZH

Reputation: 785

one way would be to limit the number of decimal place input to just one decimal place when user is entering their input.

this would be much better as it is real time instead of checking it at the end.

    private void tbx_KeyDown(object sender, KeyEventArgs e)
    {
        //mark the sneder as a textbox control so we can access its properties
        TextBox textBoxControl = (TextBox)sender;

        //if there is already a decimals, do not allow another
        if (textBoxControl.Text.Contains(".") && e.PlatformKeyCode == 190)
        {
            e.Handled = true;
        }
    }

Upvotes: 0

mikeagun
mikeagun

Reputation: 219

Assuming the input is a string, try:

if (input.IndexOf('.') == -1 || input.LastIndexOf('.') == input.IndexOf('.'))
{
    //good
}
else
    MessageBox.Show("More than one decimal point");

A better way though would be to use TryParse which will check the number for formatting

float age;
if (float.TryParse(input, out age))
{
    //good
}
else
    MessageBox.Show("Invalid age.");

Upvotes: 1

Related Questions