pv619 pv619 - 3 months ago 29
C# Question

Specified cast is not valid with field int

I keep getting the "Specified cast is not valid" error on my code in the ID column. I tried using

data.Columns.Add("ID", typeof(int));


to let it know that the ID is an int. I am getting the data from a local .xls file.

here's my code:

foreach (DataRow p in data.Rows)
{
TopPlayed top = new TopPlayed()

{
TrackID = p.Field<int>("ID"),

TrackName = p.Field<string>("Track Name"),
ArtistName = p.Field<string>("Artist Name"),
Times = p.Field<double>("NoOfPlays").ToString()
};

data.Columns.Add("ID", typeof(int));

daa.Add(top);
}


here's my class:

public class TopPlayed
{
public int TrackID { get; set; }
public string TrackName { get; set; }
public string ArtistName { get; set; }
public string Times { get; set; }
}


cheers in advance :)

Answer

Try using double instead. Excel exposes data as either strings or doubles.

TopPlayed top = new TopPlayed()

{
    TrackID = Convert.ToInt32(p.Field<double>("ID")),

    TrackName = p.Field<string>("Track Name"),
    ArtistName = p.Field<string>("Artist Name"),
    Times = p.Field<double>("NoOfPlays").ToString()
};