Kyle
Kyle

Reputation: 53

How Do I only accept Numeric Digits in C# Xamarin

I'm New to C# with Xamarin. Im using Visual Studio for Mac Preview to work on an iOS app. When Making a basic calculator I can't figure out how to not accept answers that aren't a numeric digit. For example in my Text box if I put in a letter I want an error that says

"Please enter a numeric digit".

I don't know why I'm getting an error but its not working.

When I run it and put in a number it just defaults to the else statement every time. Also with Letters. And when I put too many letters in it crashes.

    partial void AddButton_TouchUpInside(UIButton sender)
    {
        double number1 = 0.00;
        double answer = 0.00;
        double number2 = 0.00;

        int value;
        string input = Console.ReadLine();
        if (Int32.TryParse(input, out value))
        {
            number1 = double.Parse(Number1TextBox.Text);
            number2 = double.Parse(Number2TextBox.Text);
            answer = number1 + number2;
            AnswerLabel.Text = "The answer is: " + answer.ToString();                             
        }
        else
        {

            InvalidLabel.Text = "Please enter a Numeric Digit";
        }
    }   

Upvotes: 5

Views: 4202

Answers (2)

xleon
xleon

Reputation: 6365

I think the problem is string input = Console.ReadLine(); Why are you expecting a correct value with that statement? That would be valid for a console program but you are running an iOS app.

It would make sense something like:

string input = YourTextInput.Text;

If you want to restrict the text input to a keyboard with numbers, use the following:

YourTextInput.KeyboardType = UIKeyboardType.NumberPad;

And one more thing. If the answer should be a double, you should use double.TryParse(input, out value) instead of int.

What about this?

double number1 = 0.00;
double answer = 0.00;
double number2 = 0.00;

if (double.TryParse(Number1TextBox.Text, out number1)
    && double.TryParse(Number2TextBox.Text, out number2))
{
    answer = number1 + number2;
    AnswerLabel.Text = "The answer is: " + answer.ToString();                             
}
else
{
    InvalidLabel.Text = "Please enter a Numeric Digit";
}

You still need to validate the number entered, as the number pad allows to type more than one decimal point.

Upvotes: 3

Troy Poulter
Troy Poulter

Reputation: 752

I'd recommend changing the TextBox so the keyboard which appears is numeric only.

<Entry Keyboard="Numeric" />

Check out this Xamarin Guide for more info.

Upvotes: 3

Related Questions