Anyname Donotcare
Anyname Donotcare

Reputation: 11393

Unable to cast object of type 'System.Int16' to type 'System.String'

I encounter the following exception in a LINQ query .

Unable to cast object of type 'System.Int16' to type 'System.String'.


 var query = from t in dt.AsEnumerable()
                        select new
                        {
                            sys_db= t.Field<Int16>("process_id").ToString() + "|" + t.Field<string>("db_code").ToString(),
                            process_name = t.Field<string>("process_name").ToString()
                        };

Why this problem appear and how to fix it ?

Upvotes: 7

Views: 32507

Answers (2)

Ehsan
Ehsan

Reputation: 32661

Why this problem appear

This appears because you are trying to read an Int16 field to a string, which is not allowed

how to fix it

First of all identify the field which is actually an int16 and you are reading as string. From your code it is most probably this field

t.Field<string>("db_code")

you need to change it to

t.Field<Int16>("db_code")

Upvotes: 1

xanatos
xanatos

Reputation: 111820

This

t.Field<string>("db_code").ToString()

perhaps should be this:

t.Field<short>("db_code").ToString()

or equivalent

t.Field<Int16>("db_code").ToString()

Upvotes: 5

Related Questions