473,320 Members | 1,810 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Specified cast is not valid, when column returns NULL

while (dr.Read())
//dr is an instance of sqlDataReader
{
double minAirTemp = (double)(Single)dr["minAirTemp"];
// minAirTemp is column in SQLExpress table (data type: real, allows nulls)
}

The above code works. But when there are NULL, I get the following error
System.InvalidCastException: Specified cast is not valid

To solve this problem, I spent a day on Google. Finally I got a hint from http://www.codeproject.com/cs/database/SmartReader.asp and replaced the code line in while{} as follows:

double minAirTemp1 = (dr.IsDBNull(dr.GetOrdinal("minAirTemp1")))
? 9999 : double.Parse(dr["minAirTemp1"].ToString()); //9999 to respresent nulls

This works for me for now. But just wondering, whether there is a better method to deal with such a situation????

Can someone be kind to point me to some suitable reference !

Thanks !
Apr 6 '06 #1
5 8349
VS2005 has a double.TryParse

If the TryParse failes, then set the value to DBNull.Value
"Web learner" <be******@learning.edu> wrote in message
news:uW**************@TK2MSFTNGP04.phx.gbl...
while (dr.Read())
//dr is an instance of sqlDataReader
{
double minAirTemp = (double)(Single)dr["minAirTemp"];
// minAirTemp is column in SQLExpress table (data type: real, allows
nulls)
}

The above code works. But when there are NULL, I get the following error
System.InvalidCastException: Specified cast is not valid

To solve this problem, I spent a day on Google. Finally I got a hint from
http://www.codeproject.com/cs/database/SmartReader.asp and replaced the code
line in while{} as follows:

double minAirTemp1 = (dr.IsDBNull(dr.GetOrdinal("minAirTemp1")))
? 9999 : double.Parse(dr["minAirTemp1"].ToString()); //9999 to respresent
nulls
This works for me for now. But just wondering, whether there is a better
method to deal with such a situation????
Can someone be kind to point me to some suitable reference !
Thanks !
Apr 6 '06 #2
I have a big class called SqlHelper full of methods like:

public static decimal GetReaderDecimal(IDataRecord dr, int column,
decimal ifNull)
{
return dr.IsDBNull(column)? ifNull : dr.GetDecimal(column);
}

Apr 6 '06 #3
I did roughly the same thing in C# 1.1: write a static helper method to
which you pass the row, the column name, and the default value, and it
returns the value. I had one for each primitive type, including one for
strings.

In C# 2.0 there are nullable types, but I'm not sure how they are at
mediating between DbNull and null.

Apr 6 '06 #4
"Bruce Wood" <br*******@canada.com> writes:
In C# 2.0 there are nullable types, but I'm not sure how they are at
mediating between DbNull and null.


In C# 2.0 you can use the "as" operator in conjunction with nullable
types, e.g.:

IDataReader r = ...;
int? val = r["MyColumn"] as int?;

This will gracefully handle the case that r["MyColumn"] contains a
DbNull.

Best regards,
Martin
Apr 6 '06 #5
For a beginner like me,the whole scenario is overwhelmingly confusing. It is
hard to figure out what is legacy and what is cutting-edge elegant methods.

Can someone be kind to point out to latest tutorial material on this topic?
Please refer to my original messsage.

Thanks !
"Bruce Wood" <br*******@canada.com> wrote in message .
I did roughly the same thing in C# 1.1: write a static helper method to
which you pass the row, the column name, and the default value, and it
returns the value. I had one for each primitive type, including one for
strings.

In C# 2.0 there are nullable types, but I'm not sure how they are at
mediating between DbNull and null.

Apr 6 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: Jack MacRank | last post by:
Hello, I'm coding a webform application in C# (ASP.NET 1.1 SP1 with VS.NET 2003 Pro on WinXP SP2 using IIS 5.1). I created a seperate "data" class to house all the MySQL connection and sql...
3
by: PK9 | last post by:
I am looking for assistance in pinpointing the cause of the following exception. I am getting a "Specified Cast is not valid" exception on my page. I am trying to populate a datagrid. One of my...
6
by: Biva | last post by:
Hello All, Please help. I get the following error from my webpage: System.InvalidCastException: Specified cast is not valid. at Time.MaintAtRiskProjects.UpdateProject(String Project, String...
2
by: Fabian | last post by:
Hi, I work with asp.net 2.0 and I have a intermittent error, only happens a few times a day. In the page I evaluate a Query String and then I get data form a database. The code snipped: ...
15
by: David | last post by:
Hi, I have built a web application that will be a very high profile application. We had tested it, demonstrated it and shown that it all works. On a dress rehearsal run through, it failed...
5
by: Web learner | last post by:
while (dr.Read()) //dr is an instance of sqlDataReader { double minAirTemp = (double)(Single)dr; // minAirTemp is column in SQLExpress table (data type: real, allows nulls) } The above...
3
by: fniles | last post by:
I am accessing MS Access db with tblA whose column UNABLE can have NULL value. When I access UNABLE whose value is null, I got an error " Run-time exception thrown : System.InvalidCastException -...
4
by: John Rogers | last post by:
Can someone help me out if possible with this error when running a program. I have this code in the program //------------------------------------------- System.Data.OleDb.OleDbCommand vCommand...
3
by: =?Utf-8?B?UGF1bCBQcmV3ZXR0?= | last post by:
I'm attempting to use LINQ to insert a record into a child table and I'm receiving a "Specified cast is not valid" error that has something to do w/ the keys involved. The stack trace is: ...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.