locked
InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. RRS feed

  • Question

  • User1876385612 posted

    can someone suggest code to test for data type and treat it accordingly please.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.EntityFrameworkCore;
    using EarthThyme.Data;
    using EarthThyme.Models;
    
    namespace EarthThyme.Pages.Plants
    {
        public class IndexModel : PageModel
        {
            private readonly EarthThyme.Data.ConnET _context;
    
            public IndexModel(EarthThyme.Data.ConnET context)
            {
                _context = context;
            }
    
            public IList<ClsPlants> ClsPlants { get;set; }
    
            public async Task OnGetAsync()
            {
                ClsPlants = await _context.Plants.ToListAsync();
                /*           if (_context.Plants.OfType<string>)
                           {
                               ClsPlants = await _context.Plants.ToListAsync();
                           } else
                           {
                               ClsPlants = await _context.Plants.ToListAsync();
                           }
               */
            }
        }
    }
    

    Sunday, November 1, 2020 1:44 AM

All replies

  • User1120430333 posted

    can someone suggest code to test for data type and treat it accordingly please.

    http://net-informations.com/q/faq/type.html

    I don't understand the purpose. Do you not understand the exception and how to resolve it?

    Sunday, November 1, 2020 11:08 AM
  • User1876385612 posted

    the generated code is trying to parse a int field from a database into a string. how do I resolve this?

    Sunday, November 1, 2020 10:34 PM
  • User1535942433 posted

    Hi Zerkin,

    How do you return the int data?You don't post relation to us.Could you post full codes to us?

    You could use like this:

    Account_Number = result.GetInt32(0)

    https://forums.asp.net/t/2024772.aspx?Unable+to+cast+object+of+type+System+Int32+to+type+System+String+

    Best regards,

    Yijing Sun

    Tuesday, November 3, 2020 3:57 AM
  • User1120430333 posted

    the generated code is trying to parse a int field from a database into a string. how do I resolve this?

    If the int database column is really suppose to be working with string result, then you have to manually to the Cast yourself,  .NET is not going to automatically do it.

    int.Tostring() for an int type to be cast to string or use (string) int to cast the int to string

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions

    Tuesday, November 3, 2020 6:30 AM