Error CS0029 in Visual Studio

-1

I'm trying to make a simple calculator, just to understand how it works, and I came across the following problem:

If I put 5 + 5 on the calculator it gives me the value of 55 as an answer. To fix this I tried to pass the values entered to int , but it always gives the error:

  

Can not implicitly convert type 'int' to 'string'

 private void BtnSoma_Click(object sender, EventArgs e)
    {
        lblResultado.Text = Convert.ToInt32(txtNum1.Text) + Convert.ToInt32(txtNum2.Text); 
    }
    
asked by anonymous 14.12.2018 / 18:06

1 answer

1

You need to convert to integer to make the account and then convert back to string . Nothing guarantees that something will be typed correctly, and if the entered data is not an integer the application will break, to correct this another code needs to be made:

private void BtnSoma_Click(object sender, EventArgs e) {
    if (!int.TryParse(txtNum1.Text, out var valor1) || !int.TryParse(txtNum2.Text, out var valor2)) {
        MessageBox.Show("Pelo menos um dos valores é inválido", "Entrada inválida", MessageBoxButtons.YesNo);
        return;
    }
    lblResultado.Text = (valor1 + valor2).ToString(); 
}

See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference . Slightly different to be easily testable online.

    
17.12.2018 / 11:11