CS0029 error in Visual Studio

Asked

Viewed 516 times

-1

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

If I put 5+5 in the calculator it gives me the value of 55 as a response. To fix this I tried to pass the values typed to int, but always gives the error:

Cannot implicitly Convert type 'int' to 'string'

 private void BtnSoma_Click(object sender, EventArgs e)
    {
        lblResultado.Text = Convert.ToInt32(txtNum1.Text) + Convert.ToInt32(txtNum2.Text); 
    }

1 answer

1


Need to convert to whole make account and then convert again to string. Nothing guarantees that something correct will be typed, and if the input data is not an integer the application will break, to fix this need to be done another code:

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(); 
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference. Slightly different to be easily tested online.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.