Click here to Skip to main content
15,945,976 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

I am able to select multiple distinct columns from a data table using Linq.

var dsStatus = (from row in dsDefectLibary.Tables[0].AsEnumerable()
                                select new
                                    statusID = row.Field<int>("DefectStatusId")
                                    ,Status = row.Field<string>("DefectStatus")

But while displaying those selected values using foreach is giving error as 'Specified cast is not valid.'

foreach(var row in dsStatus)

Please guide me.
Thank you.
Updated 11-Mar-15 1:40am
Praveen Kumar Upadhyay 11-Mar-15 7:44am    
statusID = row.Field<int>("DefectStatusId")
,Status = row.Field<string>("DefectStatus")

Check in db 'DefectStatusId' is of Int and 'DefectStatus' is of string.
Maciej Los 11-Mar-15 15:54pm    
I tested your code and it works fine.

1 solution

The execution of your Linq-Query is deferred until you iterate over the results in the foreach-loop. See: LINQ and Deferred Execution[^]

That means that the error actually happens in the execution of the query, the Console.Writeline doesn't have any problem with it.

I assume that the column DefectStatusId is not of Type Int32 (= int). Other theoretical causes (but probably unlikely): DefectStatusId is null for some record(s) or DefectStatus is not of Type String.

Check the data type of your columns and if DefectStatusId isn't Int32 but Byte, Short (Int16) or Long (Int64) then change the "int" in statusID = row.Field<int>("DefectStatusId") to the matching Type. If you can't solve it this way, try this: statusID = Convert.ToInt32(row["DefectStatusId"])
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900