Please can any one advise me if it is possible to decalre a custom structure that can be assigned Nothing and / or DbNull.Values, and also can be instanciated as Nothing?
What I am looking to do is ceate a custom DateTime object that can recieve a DBNull.Value from a database query and also start life as Nothing. IS this possible?
Thanks in advance.
Best regards, Duane
Seems like Nullable<DateTime>
( DateTime?
for short, or Date?
in VB.NET) gets you almost all the way there. You just need to specially deal with the conversion to/from DBNull
on your own.
// You can set a DateTime? to null.
DateTime? d = null;
// You can also set it to a DateTime.
d = DateTime.Now;
// You can check whether it's null in one of two ways:
if (d == null || !d.HasValue) // (These mean the same thing.)
{ }
// Boxing a DateTime? will either result in null or a DateTime value.
SetDatabaseValue(d);
// As for conversions from DBNull, you'll have to deal with that yourself:
object value = GetDatabaseValue();
d = value is DBNull ? null : (DateTime?)value;
If you're working with DataSets, use the Field and SetField DataRow extension methods . These allow you to use Nullable types without worrying about DBNull anymore.
Eg, suppose the "MyDateField" field (of type DateTime) is nullable. Then you can do something like this:
foreach (var row in myDataTable)
{
// will return null if the field is DbNull
var currentValue = row.Field<DateTime?>("MyDateField");
// will set the value to DbNull.Value
row.SetField<DateTime?>("MyDateField", null);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.