Mr.Rendezvous
Mr.Rendezvous

Reputation: 1993

Specified cast is not valid for different table?

Well here is the situation, from the table before I running this code is run perfectly. But when I change the table is getting error, while I think is not, because T_TEMPLATE_ID field is also an "int" just like the table before.

the error is: Specified cast is not valid

here's the code:

       DataTable dt;
       dt = getDownload(); // << here dt get table

       int iTemplateId = 3;
       IEnumerable<DataRow> query;

       try
       {
            query =
                from t in dt.AsEnumerable()
                where t.Field<double>("T_TEMPLATE_ID") == iTemplateId
                select t;

            // here comes the error
            dt = query.CopyToDataTable<DataRow>();
       }
       catch (Exception exp)
       {
            MessageBox.Show("Error: " + exp.Message, "Error");

       }

so what is the problem, am I getting wrong in other place? I'm sorry if it's not clear enough, you can ask for more information :)

thanks before

Upvotes: 0

Views: 2033

Answers (2)

BizApps
BizApps

Reputation: 6130

@Mr.Rendezvous could you try this:

Check if test will have a result. Add breakpoint on test and on boundTable.

            IEnumerable<DataRow> test =
            from t in dt.AsEnumerable()
            where Convert.ToInt32(t["T_TEMPLATE_ID"]) == iTemplateId
            select t;

            if(test.count() > 0)
            {
            //recods Found!
            DataTable boundTable  = test.CopyToDataTable<DataRow>();
            }
            else
            {
              //no Recods found!
            }

DataTableExtensions.CopyToDataTable(Of T) Method (IEnumerable(Of T)) MSDN

Regards

Upvotes: 1

Jeff Mercado
Jeff Mercado

Reputation: 134801

It sounds like your field type is not actually a double but an int. Your query tries to (implicitly) unbox an int as a double causing the cast error. Change the query so the field is read as an int.

from t in dt.AsEnumerable()
where t.Field<int>("T_TEMPLATE_ID") == iTemplateId
select t;

Upvotes: 0

Related Questions