Convert string to integer

2

I'm not able to convert the text from my TextBox to integer.

namespace Pag98_Exe1
{
    public partial class frmveiculos : Form
    {
        public frmveiculos()
        {
            InitializeComponent();
        }

        Veiculos veiculos = new Veiculos(); //Declarando a classe veiculos

        private void btnenviar_Click(object sender, EventArgs e)
        {
            if(mskTxtplaca.Text != "" && cbxmarca.Text != "" && txtanofabricacao.Text != "")
            {
                veiculos.Placa = mskTxtplaca.Text; //Atribuindo o valor de Placa ao texto do TextBox
                veiculos.Marca = cbxmarca.Text;
                veiculos.AnoFabricacao(int.Parse(txtanofabricacao.Text)); //Passando o valor do TextBox para inteiro e atribuindo ao TextBox
            }
        }
    }
}
    
asked by anonymous 21.10.2016 / 02:44

2 answers

4

As the text comes from a control that the user can type there is no guarantee that the text can be converted to integer, so you have to try to do it, if it works right do what you want, otherwise you need to treat it somehow, issue an error, put a default value, something like that. This is done using the TryParse() method. Other solutions are flawed, do not use unless you're sure the value can be converted, which does not seem to be the case. I have my doubts if the rest of the logic is adequate, but I can not speak without knowing the requirements.

private void btnenviar_Click(object sender, EventArgs e) {
    if(mskTxtplaca.Text != "" && cbxmarca.Text != "" && txtanofabricacao.Text != "") {
        veiculos.Placa = mskTxtplaca.Text;
        veiculos.Marca = cbxmarca.Text;
        int anoFabricacao;
        if (int.TryParse(txtanofabricacao.Text, out anoFabricacao) {
            veiculos.AnoFabricacao = anoFabricacao;
        } else {
            //aqui coloque o que deve fazer se a conversão falhar
        }
    }
}

In C # 7 you can make it a little simpler:

private void btnenviar_Click(object sender, EventArgs e) {
    if(mskTxtplaca.Text != "" && cbxmarca.Text != "" && txtanofabricacao.Text != "") {
        veiculos.Placa = mskTxtplaca.Text;
        veiculos.Marca = cbxmarca.Text;
        if (int.TryParse(txtanofabricacao.Text, out var anoFabricacao) {
            veiculos.AnoFabricacao = anoFabricacao;
        } else {
            //aqui coloque o que deve fazer se a conversão falhar
        }
    }
}
    
21.10.2016 / 02:56
2

Your post is a bit confusing, from what I understand the code tries this solution:

veiculos.AnoFabricacao = int.Parse(txtanofabricacao.Text);
    
21.10.2016 / 02:51