System.InvalidCastException

  • Thread starter Thread starter Kini
  • Start date Start date
K

Kini

Howdy!

Code
-----
string dtsSearchReq ="";
while (myReader.Read()) {
for(int j=0;j<myReader.FieldCount;j++) {
if (myReader.IsDBNull(i)) dtsSearchReq += myReader.GetString(i);

}
}

Background
----------
In the above code, I am using an OdbcDataReader to read the fields of
retrieved records. I am using a system DSN to connect to an MS-XL
spreadsheet.

There are 17 fields, 16 of which correspond to "string" datatype and 1
corresponds to "double". However, I would like to recieve all fields as
"string". One of the string fields in the database has a NULL value.

Problem
-------
When I use the IsDBNull check, myReader.GetString(i) fails at a field
with "double" datatype. System.InvalidCastException is raised. Note
that the "double" field contained a value of 1 and not a NULL.

When I do away with IsDBNull check, as expected, myReader.GetString(i)
fails when it encounters the NULL value. However, the "double" field
when encountered, is successfully converted to a corresponding text
representation (namely 1.00).

Summary: myReader.GetString(i) succesfully converts a "double" to
"string" in the absense of IsDBNull, but fails to do so in its
presence!

can anyone please throw some light?
 
How about:

for(int j=0;j<myReader.FieldCount;j++)
{
object o = myReader.GetValue(j) ;
if ( o != DBNull.Value )
dtsSearchReq += o.ToString();
}
 
Hello Mohammad,

Your code works great! Thank you very much.

Any hint why mine was failing?
 
Kini said:
Hello Mohammad,

Your code works great! Thank you very much.

Any hint why mine was failing?

Yes - you were calling GetString on a column which wasn't a string. You
should almost always just call the appropriate method based on the type
of the column.

By the way, it helps to post your *actual* code rather than typing it
in again - your initial posted code would have failed because it was
trying to call GetString on all null values rather than all non-null
values.
 

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

Similar Threads

GetString(4) is null 3
Reader parameters 1
returning a struct 1
dll 5
run test code 4
How deal with nulls in SQLDataReader? 4
One field, multiple properties 2
Getting Null Value Error when Inserting record 1

Back
Top