OleDbDataReader.GetString Exception - Specified cast is not valid

When my C# (.NET 3.5) application attempts to access a MS Access 2007 database the OleDbReader.GetString() method is throwing an exception:

Specified cast is not valid.

What am I doing wrong?

OleDbCommand cmd = null;
OleDbDataReader reader = null;
String queryString = "SELECT ids.ENUM_H, bas.[BAS BACnet Object Type/Instance] FROM [OV2 BAS] AS bas INNER JOIN [OV2 RefID] AS ids ON bas.[Ref ID] = ids.[Ref ID]";


    cmd = new OleDbCommand(queryString, this._conn);
    reader = cmd.ExecuteReader();

    if (!reader.HasRows)
        Exception e = new Exception("Read of mapping table returned no results.");
        throw e;
        while (reader.Read())
            Int32 index;
            String classTypeString = null; // = reader.GetString(reader.GetOrdinal(MappingTable.OBJECT_IDENTIFIER_COLUMN_NAME)).Substring(0, 2);
            int it = reader.GetOrdinal(MappingTable.OBJECT_IDENTIFIER_COLUMN_NAME);
            string st = reader.GetString( it );  // <-- **Exception is thrown here** <--
            st = st.Substring(0,2);
            String classIdString = reader.GetString(reader.GetOrdinal(MappingTable.OBJECT_IDENTIFIER_COLUMN_NAME)).Substring(2);

            index = Convert.ToInt32(classIdString);
            ClassIds[index, 0] = reader.GetString(reader.GetOrdinal("ENUM_H"));
            ClassIds[index, 1] = classTypeString;
catch (Exception e)
    Console.WriteLine("ERROR: " + e.Message);
    throw e;


I know that the Open() and Close() methods work. Something is wrong with my query, or the way I am processing the results. Thanks.


Okay, so reader.IsDBNull(1) is returning true... which means there's no data in that particular row for that field.

You need to work out what that means, and handle it appropriately. You may want to modify the query to not include such rows, or use reader.IsDBNull to detect such rows and act appropriately, e.g. using a default value for the field.

Need Your Help

Multiple linq queries or just build a SQL view?

sql-server asp.net-mvc performance linq

I have a mvc view that requires data from 5 different DB tables. I currently have a big LINQ query that joins all the tables and returns the results, works fine. However, I am wondering if it would

Complex use of JTable, TableModel and others

java swing jtable tablemodel defaulttablemodel

I have some problems with the manage of two JTable, and relative data.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.