System.InvalidCastException

M

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();
}
 
M

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top