user3127227
user3127227

Reputation: 37

specified cast is not found

I'm trying to return a list consisting of some elements (sql query) but the debugger stops at the director.oscars line.

I declared oscars as a private int and the data from the database is all correct.

If I omit that one line there is no error anymore and a list is returned with the whole oscars column full of 0's.

  public static List<Director> AllDirectors()
    {
        string command;
        command = "SELECT directorId, firstName, lastName, birthdate, gender, oscars " +
            " FROM directors order by directorId";
        OleDbDataAdapter adapter = new OleDbDataAdapter(command, connectionString);
        DataTable datatable = new DataTable();
        adapter.Fill(datatable);


        List<Director> list = new List<Director>();
        for (int i = 0; i < datatable.Rows.Count; i++)
        {
            Director director= new Director();
            director.directorId = datatable.Rows[i].Field<int>("directorId");
            director.firstName = datatable.Rows[i].Field<string>("firstName");
            director.lastName= datatable.Rows[i].Field<string>("lastName");
            director.oscars = datatable.Rows[i].Field<int>("oscars");
            director.birthdate = datatable.Rows[i].Field<DateTime>("birthdate");
            director.gender = datatable.Rows[i].Field<string>("gender");




            list.Add(Director);
        }
        return list;

Upvotes: 1

Views: 119

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726909

The most likely reason for the invalid cast exception is that the oscars field in the database is not an int.

Check the exact type of the field, and replace int in datatable.Rows[i].Field<int>("oscars") with the correct type. For example, if the field is nullable integer, you would need to use datatable.Rows[i].Field<int?>("oscars"); (with a question mark).

Note: if Director.oscars is non-nullable, but the database field is, use ?? to replace nulls with zeros, like this:

director.oscars = datatable.Rows[i].Field<int?>("oscars") ?? 0;

Upvotes: 3

Related Questions