How to fix the error - Unable to cast object of type 'System.Int32' to type 'System.String'

BenTam 1,781 Reputation points
2024-01-09T04:42:36.14+00:00

Dear All,

How to fix the error - Unable to cast object of type 'System.Int32' to type 'System.String'

Student

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2024-01-09T06:54:29.1766667+00:00

    Hi @BenTam-3003 , Welcome to Microsoft Q&A,

    Because the StudentID you selected is int32.

    Try using tostring() to convert it to string first.

    string tmp = string.Format("{0}", row.Field<int>("StudentID").ToString());
    

    In this code, I've replaced row.Field<string>("StudentID") with row.Field<int>("StudentID").ToString() to explicitly convert the integer value to a string before using it in the string.Format method. This should resolve the casting issue.

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.