How do I add or subtract a digit in the TextBox with a button?

4

I want to add a number to a TextBox by generating a number when the user clicks the "+" button and subtracts when clicking "-". For example: the random number was 2. If I click on the +, it appears 3. If I click on -, the 1 appears.

It seems that you can not do add and subtract type operations with TextBox s, as in this code here, that the CS00019 error was displayed:

private void btn_plus_Click(object sender, EventArgs e)
{ 
resultado.Text = resultado + 1;
}

Where resultado.Text is the number converted to string and resultado the name of my TextBox .

How could I make it work?

    
asked by anonymous 25.08.2015 / 16:54

3 answers

4

Use TryParse() if you do not want it to generate an error if the value is invalid. You can treat as you wish if it is invalid. In this case I ignored the sum.

private void btn_plus_Click(object sender, EventArgs e) {
    int numero;
    if (int.TryParse(resultado.Text, out numero)) {
        resultado.Text = (numero + 1).ToString();
    }
}

See running on dotNetFiddle . I had to adapt since I'm not in a WinForms application.

Only use the Parse ( difference ) whenever it raises an exception if it can not parsear the number, which is not common to want this. It's better to know that you've made a mistake and treat it right there without the cost of the exception, even more that most programmers treat exceptions in the wrong way.

    
25.08.2015 / 17:13
0

OC # is not like PHP that performs operations with what lies ahead , it needs to work with certain types, and how you yourself expressed the value of the TextBox field is text (or string ). To work with mathematical operations you must first convert the value to some numeric type such as Int , Float and etc ...

Then your code would look like ...:

To add:

resultado.Text = (int.Parse(resultado.Text) + 1).ToString();

Or to Subtract:

resultado.Text = (int.Parse(resultado.Text) - 1).ToString();
    
25.08.2015 / 16:57
0
private void btn_plus_Click(object sender, EventArgs e)
{ 
    int boxI = resultado.Text        
    resultado.Text = boxI + 1;
}

I did not have time to test, but it should work.

    
30.09.2015 / 00:29