-1

i have tried looking for some scources on how to make the user only enter numbers instead of letters. i want to display a message on that so the user knows they need to type in a number. i would like some pointers on how to impliment that condition.

(this is done in WPF c# visual studio)

private void Add_Click(object sender, RoutedEventArgs e)
    {
       //text box
      number1 = Convert.ToInt32(TextBox1.Text);
      number2 = Convert.ToInt32(TextBox2.Text);

        //if number1 and number2 are less than 1
        if (number1 < 1 || number2 < 1|| number1 > 100 || number2 > 100)
            {
                MessageBox.Show("INVALID INPUT");
                TextBox1.Text = " ";
                TextBox2.Text = " ";
            }
        else if (!success)
        {
            MessageBox.Show("Type a number please.");
            success = int.TryParse(TextBox1.Text, out number1);
            success = int.TryParse(TextBox2.Text, out number2);

        }
        //operation
        answer = number1 + number2;
        //
        //when clicked
        answerText.Text = answer.ToString();
        }`
ninten
  • 13
  • 4

1 Answers1

2

You are going about it the wrong way. In WPF, you can do "binding" to a public getter/setter of a given type. The framework itself does the converting and allows proper value or not without you having to try and parse it.

For example, in your code-behind (.cs portion), create a public property for what you are using for input. Ex:

// This is a public getter/setter for binding and defaults its value to 27.
public int MyTextInput {get; set; } = 27;

The only reason I am setting the default to 27 is so when you get the binding done and run the form, you know it is working properly if the form shows 27 when initially displayed. If not, then your binding / data context is not correct and have to fix that part first. But once its done, you should be good and can change the default back to 0.

Then, in the single textbox on the form wide enough to show 2 digits, set the binding to this property something like (you may need to specify a grid row/column if your form is so established with a grid for alignment).

    <TextBox Text="{Binding MyTextInput}" MaxLength="2" />

Now, when you run the form, the textbox control will be "bound" to your class's public property "MyTextInput" as an integer data type. If you try to put in charaacters, wpf will automatically show the box with a red border indicating an invalid value.

Then, in whatever your click / button handler is, you can just look at the "MyTextInput" value and go accordingly.

Obviously if you have multiple actual values you are expecting, just create two public properties and two textbox entries each bound to a respective public property you make available.

DRapp
  • 47,638
  • 12
  • 72
  • 142