Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Object cannot be cast from DBNull to other type
Message
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Versions des environnements
Environment:
C# 4.0
OS:
Windows 7
Network:
Windows 2003 Server
Database:
MS SQL Server
Application:
Web
Divers
Thread ID:
01574643
Message ID:
01574718
Vues:
93
This message has been marked as a message which has helped to the initial question of the thread.
DbNull is not the same as null. DbNull is an static object that has a single static .Value property. DbNull.Value gives the Singleton instance of a DbNull object.

That said you can't treat DbNull like a null - you have to check for DbNull and convert the value.
object time = row["start_time"]';

// convert dbNull into a real null
if (time == DbNull.Value)
   time = null;

DateTime start_time = Convert.ToDateTime((time ?? DTSqlMinDate));
But - if you really shouldn't be doing this in your application code. This is the job of a business or data layer to pull out values from a DataRow and automatically turn it into something that's more usable on an application level...

FWIW, I've never really understood ADO.NET's reasoning for providing a database specific null type. This logic has so many crappy implications in framework code and especially in end user code such as your's. I think it was originally designed to differentiate database nulls from nulls that could be returned on failures, but that was really a bad design choice that still plagues us today.

+++ Rick ---



>
object field =


>Hi everybody,
>
>I am getting this error
>
>"Object cannot be cast from DBNull to other types"
>
>on this piece of code:
>
>start_time = Convert.ToDateTime((row["start_time"] ?? DTSqlMinDate));
>
>As you see here, I attempt to use C# coalesce operator in order to avoid this error, but it doesn't work. How should I correct this error without introducing extra nullable datetime variable?
>
>Thanks in advance.
>
>UPDATE. This seems to fix the problem
>
>Convert.ToDateTime((row["start_time"]== DBNull.Value)?DTSqlMinDate:row["start_time"]);
+++ Rick ---

West Wind Technologies
Maui, Hawaii

west-wind.com/
West Wind Message Board
Rick's Web Log
Markdown Monster
---
Making waves on the Web

Where do you want to surf today?
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform