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

2
protected void btnSave_Click(object sender, EventArgs e)
    {
        List<ProdutoAmortizacaoCreditoDias> aDay = new List<ProdutoAmortizacaoCreditoDias>();
        ProdutoAmortizacaoCreditoDias ee = new ProdutoAmortizacaoCreditoDias();


        if (ProcessingType == 1)
        {


            ee.Dia = this.txtDay.Text;        

        }
        else
        {
            ee.Dia = this.lblDay.Text;
            ee.FromProductID = this.hdnSourceID.Value;
            ee.ToProductID = this.hdnDestinationID.Value;
        }

The error is in:

ee.Dia = this.txtDay.Text;

Error:

  

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

I realize that you can not convert from string to int .

How can I get around this?

    
asked by anonymous 10.02.2017 / 18:57

3 answers

4

You have to have the conversion done. As the data may not be valid you have to test to see if the conversion ran correctly. This is done with TryParse() .

protected void btnSave_Click(object sender, EventArgs e) {
    var aDay = new List<ProdutoAmortizacaoCreditoDias>();
    var ee = new ProdutoAmortizacaoCreditoDias();
    int dia;
    if (int.TryParse(this.txtDay.Text, out dia)) {
        ee.Dia = ee.Dia = dia;
    } else {
        //faz alguma coisa aqui porque deu erro na conversão.
    }
    if (ProcessingType != 1) {
        ee.FromProductID = this.hdnSourceID.Value;
        ee.ToProductID = this.hdnDestinationID.Value;
    }

I placed it on GitHub for future reference .

In C # 7 you can only do:

protected void btnSave_Click(object sender, EventArgs e) {
    var aDay = new List<ProdutoAmortizacaoCreditoDias>();
    var ee = new ProdutoAmortizacaoCreditoDias();
    if (int.TryParse(this.txtDay.Text, out var dia)) {
        ee.Dia = ee.Dia = dia;
    } else {
        //faz alguma coisa aqui porque deu erro na conversão.
    }
    if (ProcessingType != 1) {
        ee.FromProductID = this.hdnSourceID.Value;
        ee.ToProductID = this.hdnDestinationID.Value;
    }

I took the opportunity to give an organized one in the code.

    
10.02.2017 / 19:12
2

Using c # just use the system's conversion class.

ee.Dia = System.Convert.ToInt32(this.lblDay.Text);

Detail: This conversion is if Dia is an int. If it is a long , use ToInt64 ; if it is a short, use ToInt16 .

More on link

    
10.02.2017 / 19:12
0

Your Day property is probably of type Int, when you get this.lblDay.Text; the text by default is a string, so you can not assign a string to an Int type, you would have to convert before this:

ee.Dia =  Convert.ToInt32(this.lblDay.Text);

OR

ee.Dia =  int.Parse(this.lblDay.Text);

I believe it will work, but it's okay to validate that this field really is an integer value, you can do this with the int.TryParse example HERE

    
10.02.2017 / 19:10