2

I can not understand why "Specified cast is not valid exception" is thrown here:

c# code:

the exception throws when it reaches to m.HadapGoalPercent property, i tryed to change the datatype of x => x.Field<float>("HadapGoalPercent") also to single and double but its not working

 for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        Sales.Month m = new Sales.Month(Yearnum, (byte)(i+1));
                        m.HadapGoal = dt.AsEnumerable().Where(x => x.Field<int>("MonthNum") == i + 1).Select(x => x.Field<int>("HadapGoalIncome")).Single();
                        m.ShotefGoal = dt.AsEnumerable().Where(x => x.Field<int>("MonthNum") == i + 1).Select(x => x.Field<int>("ShotefGoalIncome")).Single();
                        m.HadapGoalPercent = dt.AsEnumerable().Where(x => x.Field<int>("MonthNum") == i + 1).Select( x => x.Field<float>("HadapGoalPercent")).SingleOrDefault();
                        m.ShotefGoalPercent = dt.AsEnumerable().Where(x => x.Field<int>("MonthNum") == i + 1).Select(x => x.Field<float>("ShotefGoalPercent")).SingleOrDefault();
                        months.Add(m);
                    }

thats the definitions of ShotefGoalPercent and HadapGoalPercent properties inside Month Class:

 public Single ShotefGoalPercent { get; set; }
 public Single HadapGoalPercent { get; set; }

thats dt datatable:

(HadapGoalPercent and ShotefGoalPercent are defined as decimal(5,4) in sql database)

dt Datatable Image

thank you very much for your time and considiration

Jonathan Applebaum
  • 5,738
  • 4
  • 33
  • 52
  • Have you tried casting to decimal? After all, you said it's stored in the DB as a decimal. – sr28 Jul 27 '16 at 08:31
  • Take a look at `dt.Columns["HadapGoalPercent"].DataType` property. It should tell you what cast you need to use. – Ivan Stoev Jul 27 '16 at 08:33
  • ok...thanks to @sr28 the problem was solved i have changed HadapGoalPercent , ShotefGoalPercent from single to decimal and the datatatpe in query to decimal also...its working. here is a thread i found now about the difference between decimal, float, single and double: http://stackoverflow.com/questions/618535/difference-between-decimal-float-and-double-in-net. why not write it as an answer? - thanks again – Jonathan Applebaum Jul 27 '16 at 08:40

1 Answers1

1

As per my comment I'm not sure why you aren't just casting as a decimal, as that's what you've stored it as in the DB. However, if you really want this as a double you can try:

Convert.ToDouble(value)

With the size of decimals you're passing in you should be fine. With very large decimals you run the risk of losing precision, but as I say, I don't think this will be an issue for you.

sr28
  • 4,728
  • 5
  • 36
  • 67