error "Unable to cast object of type 'System.Int32' to type 'System.Collections.Generic.List`1[System.Int32]'"

13,766

The error message says it all - the DriverId field in each row is an int, not a List<int>. Ditto for DriverName being a string, not a List<string>. You should change your DriverId and DriverName properties to be int and string respectively, then cast to the right type too:

public class DeliveryDriver
{
    public int DriverID { get; set; }
    public string DriverName { get; set; }
}

...

foreach (DataRow dr in dsDriverID.Tables[0].Rows)
{
    IDeliveryDriver.Add(new DeliveryDriver
    {
        DriverID = (int) dr["DriverId"],
        DriverName = (string) dr["DriverName"]
    });
}

After all, each delivery driver does only have one name and one ID, don't they?

Share:
13,766
Elsa
Author by

Elsa

(csharpnewbie) The more I learn .Net, the more there is to learn....

Updated on June 29, 2022

Comments

  • Elsa
    Elsa almost 2 years

    I have an package delivery application and I am getting an error in my code below:

    public class DeliveryDriver
    {
        public List<int> DriverID { get; set; }
        public List<string> DriverName { get; set; }
    }
    
    var IDeliveryDriver = new List<DeliveryDriver>();
    
    foreach (DataRow dr in dsDriverID.Tables[0].Rows)
    {
        IDeliveryDriver.Add(new DeliveryDriver
        {
            DriverID = (List<int>)dr["DriverId"],
            DriverName = (List<string>)dr["DriverName"]
        });
    }
    

    The error occurs at the IDeliveryDriver.Add line and it goes into a catch block. The error is:

    Unable to cast object of type 'System.Int32' to type 'System.Collections.Generic.List`1[System.Int32]'

    What is causing the error?