-1

I need particular columns from datatable to bind it in DataGridView. I have following column.

Work1     Price     Area     que   Len     bre      size
A              12           x         1        1.2      1        1.2
A              12           y         2      2          2.2     4.4
A             12            z         3      11       1          11

Above is my data table and I need specifyed column i.e Area, Que, bre, size [Que * (bre * Len)]
To get this type of data I had used following Linq-to-DataTable query.

 var data = dt.AsEnumerable().Select
                (r => new
                {
                    Area = r.Field<string>("Area"),
                    Que = r.Field<int>("Quantity"),
                    Breath = r.Field<decimal>("Breath"),
                    Length = r.Field<decimal>("Length"),
                    totLen = r.Field<int>("Quantity") * (r.Field<decimal>("Breath") * r.Field<decimal>("Length"))
                }).ToList();

But its not working, It gives no value, I don't know why?? Can any one tell me how can I do this? And if there is any other alternate option is available than I love to see that...

Sagar Upadhyay
  • 819
  • 2
  • 11
  • 31
  • 3
    What does give no value, the whole query or the field `totLen`? How have you tried to evaluate the query, where are you using it? Are you sure that there's no exception that is (silently) caught? – Tim Schmelter Jan 21 '13 at 12:11
  • It gives error "Specified cast is not valid." – Sagar Upadhyay Jan 21 '13 at 12:18
  • So it is clear, you need to cast your fields to the correct type. Check the datatype of each columns in your table and cast accordingly in the linq query. – Kaf Jan 21 '13 at 12:21

1 Answers1

0

It gives error "Specified cast is not valid."

So you're getting an InvalidCastException in the Field extension method.

You have to check which column's type does not match to the one you've specified, for example:

totLen = r.Field<int>("Quantity") * r.Field<decimal>("Breath") * r.Field<decimal>("Length")

Above will fail if any of the three columns has a different type than the one you've provided. Maybe Breath is not a decimal but a double.

Edit your question and provide the types in database and we could help to identify the correct types.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939