Home All Groups Group Topic Archive Search About

System.InvalidCastException

Author
7 Aug 2006 2:42 PM
mbarb5ne
Newbie with this stuff.

Trying to start small and just read a line in from a database to see
what happens.  Not even really trying to do anything with it yet.  When
I try to read in the return statement using GetString, I get a
System.InvalidCastException.  I thought handling the null case would
take care of it, but apparently there is something else wrong as well.

Here's my code:
        static void Main()
        {
            string databaseReturn = null;

            OleDbConnection dbConnection = new
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source =
...\\..\\msds.mdb");

            OleDbCommand dbCommand = new OleDbCommand("select * from
FreeText", dbConnection);

            try
            {
                dbConnection.Open();
            }
            catch (System.Data.OleDb.OleDbException e)
            {
                String errMsg = "Error Message: " + e.Message;
            }

            OleDbDataReader dbReader = dbCommand.ExecuteReader();

            while (dbReader.Read())
            {
                if (dbReader.IsDBNull(0))
                    databaseReturn = "";
                else
                    databaseReturn = dbReader.GetString(0);
            }

            dbReader.Close();

            dbConnection.Close();
        }

Author
7 Aug 2006 3:06 PM
mbarb5ne
First off, it was producing a "Specified cast is not valid" type, which
was throwing me until I realized the field in the database that I was
trying to get was an int, not a string.

My bad, but changing the call for an integer solved my problem.

AddThis Social Bookmark Button