473,795 Members | 2,805 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

set a DateTime to NULL

I want to set a DateTime field to Null before passing it to the DB

//First I check to see if anything is in this datarow column, because
sometimes we have no data.
DateTime dt;
if ( datarow["date"].ToString().Len gth > 0)
{
//We assume the data is a date
dt = (DateTime)datar ow["date"];
}
else
//We have no data in this column
{
dt = DBNull.Value; //this does not work
}

Then I set the param.

cmdUpdate.Param eters.Add("@inv oicedate", SqlDbType.NVarC har, 40).Value =
dt.ToShortDateS tring();

If there is a date in 'datarow["date"]' everything works fine, but if there
is no data it throws an exception. So I set up the if statement to check for
something in that column, if there is something I assume it's a date and
assign it to dt. But if there no data I want to asign nothing to dt.

Thanks

Paul
Nov 16 '05 #1
6 15016
Pa******@newsgr oup.nospam <Pa******@newsg roup.nospam> wrote:
I want to set a DateTime field to Null before passing it to the DB
You just can't do that. A DateTime can't be null. It can't be
DBNull.Value, either (which is something different).
//First I check to see if anything is in this datarow column, because
sometimes we have no data.
DateTime dt;
if ( datarow["date"].ToString().Len gth > 0)
{
//We assume the data is a date
dt = (DateTime)datar ow["date"];
}
else
//We have no data in this column
{
dt = DBNull.Value; //this does not work
}

Then I set the param.

cmdUpdate.Param eters.Add("@inv oicedate", SqlDbType.NVarC har, 40).Value =
dt.ToShortDateS tring();
Yikes - is the field in the database really a string rather than a
date-related type? That's nasty.
If there is a date in 'datarow["date"]' everything works fine, but if there
is no data it throws an exception. So I set up the if statement to check for
something in that column, if there is something I assume it's a date and
assign it to dt. But if there no data I want to asign nothing to dt.


You can't do that. What you can do is:

object parameterValue;

if (!datarow.IsNul l("date"))
{
parameterValue = ((DateTime)data row["date"]).ToShortDateSt ring();
}
else
{
parameterValue = DBNull.Value;
}
cmdUpdate.Param eters.Add ("@invoicedate" , SqlDbType.NVarC har,
parameterValue) ;

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
I also had to use an if statement. I actually wrote a function to do it
for me. I know there has to be a a cleaner way but i couldnt find one.
Heres mine:

private object returnNullIfBla nk(object s)
{
if (s==null | s.ToString()==" " | s == (object)
System.DateTime .MinValue)
return System.Data.Sql Types.SqlString .Null;
//return System.Data.Sql Types.SqlDateTi me.Null;
else
return s;
}
so you might want a line like this:
dt=System.Data. SqlTypes.SqlDat eTime.Null

unlikely put you may possibly want this as a last resort:
(CAST_ME) System.Data.Sql Types.SqlString .Null
-Dwight
http://logical4.com

Nov 16 '05 #3
..NET 1.1 atleast does not support nullable value types. Even with .NET 2.0,
nullable value types donot fully solve this problem. You have to use the
DBNull structure to get around this issue as Jon explained.

- Sahil Malik
http://codebetter.com/blogs/sahil.malik/
<Pa******@newsg roup.nospam> wrote in message
news:DF******** *************** ***********@mic rosoft.com...
I want to set a DateTime field to Null before passing it to the DB

//First I check to see if anything is in this datarow column, because
sometimes we have no data.
DateTime dt;
if ( datarow["date"].ToString().Len gth > 0)
{
//We assume the data is a date
dt = (DateTime)datar ow["date"];
}
else
//We have no data in this column
{
dt = DBNull.Value; //this does not work
}

Then I set the param.

cmdUpdate.Param eters.Add("@inv oicedate", SqlDbType.NVarC har, 40).Value =
dt.ToShortDateS tring();

If there is a date in 'datarow["date"]' everything works fine, but if
there
is no data it throws an exception. So I set up the if statement to check
for
something in that column, if there is something I assume it's a date and
assign it to dt. But if there no data I want to asign nothing to dt.

Thanks

Paul

Nov 16 '05 #4
> You just can't do that. A DateTime can't be null. It can't be
DBNull.Value, either (which is something different).
yea , and just to confirm that it is because that value types cant be null
and they are always initialized to there respective default values, unless
they accept a constructor for custom initial values. Right?

Ab.

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** @msnews.microso ft.com... Pa******@newsgr oup.nospam <Pa******@newsg roup.nospam> wrote:
I want to set a DateTime field to Null before passing it to the DB


You just can't do that. A DateTime can't be null. It can't be
DBNull.Value, either (which is something different).
//First I check to see if anything is in this datarow column, because
sometimes we have no data.
DateTime dt;
if ( datarow["date"].ToString().Len gth > 0)
{
//We assume the data is a date
dt = (DateTime)datar ow["date"];
}
else
//We have no data in this column
{
dt = DBNull.Value; //this does not work
}

Then I set the param.

cmdUpdate.Param eters.Add("@inv oicedate", SqlDbType.NVarC har, 40).Value =
dt.ToShortDateS tring();


Yikes - is the field in the database really a string rather than a
date-related type? That's nasty.
If there is a date in 'datarow["date"]' everything works fine, but if there is no data it throws an exception. So I set up the if statement to check for something in that column, if there is something I assume it's a date and
assign it to dt. But if there no data I want to asign nothing to dt.


You can't do that. What you can do is:

object parameterValue;

if (!datarow.IsNul l("date"))
{
parameterValue = ((DateTime)data row["date"]).ToShortDateSt ring();
}
else
{
parameterValue = DBNull.Value;
}
cmdUpdate.Param eters.Add ("@invoicedate" , SqlDbType.NVarC har,
parameterValue) ;

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #5
Thank you Jon,

That works just fine.

I know the DB field should be Date and not string but in this certain
instance it needs to be a string.

Thank you for your help.

Paul

"Jon Skeet [C# MVP]" wrote:
Pa******@newsgr oup.nospam <Pa******@newsg roup.nospam> wrote:
I want to set a DateTime field to Null before passing it to the DB


You just can't do that. A DateTime can't be null. It can't be
DBNull.Value, either (which is something different).
//First I check to see if anything is in this datarow column, because
sometimes we have no data.
DateTime dt;
if ( datarow["date"].ToString().Len gth > 0)
{
//We assume the data is a date
dt = (DateTime)datar ow["date"];
}
else
//We have no data in this column
{
dt = DBNull.Value; //this does not work
}

Then I set the param.

cmdUpdate.Param eters.Add("@inv oicedate", SqlDbType.NVarC har, 40).Value =
dt.ToShortDateS tring();


Yikes - is the field in the database really a string rather than a
date-related type? That's nasty.
If there is a date in 'datarow["date"]' everything works fine, but if there
is no data it throws an exception. So I set up the if statement to check for
something in that column, if there is something I assume it's a date and
assign it to dt. But if there no data I want to asign nothing to dt.


You can't do that. What you can do is:

object parameterValue;

if (!datarow.IsNul l("date"))
{
parameterValue = ((DateTime)data row["date"]).ToShortDateSt ring();
}
else
{
parameterValue = DBNull.Value;
}
cmdUpdate.Param eters.Add ("@invoicedate" , SqlDbType.NVarC har,
parameterValue) ;

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #6
Abubakar <em**********@y ahoo.com> wrote:
You just can't do that. A DateTime can't be null. It can't be
DBNull.Value, either (which is something different).


yea , and just to confirm that it is because that value types cant be null
and they are always initialized to there respective default values, unless
they accept a constructor for custom initial values. Right?


It's not really due to custom initial values - it's because null is a
reference, and the value of a value type isn't a reference, so can't be
null.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #7

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

Similar topics

7
2615
by: MP | last post by:
Hello, I am trying to write a class that will expose some properties. One of the property is extracted from a SQL database and can be NULL or some integer value. Is there a elegant way of implementing this in C# ? I do not want to use variant (or similar types) because I want to retain a strnong types property. Will I have no choices but to add another property that would set/get the NULL value?
7
3857
by: JJ | last post by:
Hi, What's the correct code for checking if a DateTime control is empty or not filled in with a date? Thanks, JJ
2
4224
by: John S | last post by:
Does anyone know why the dataset blows up when it is reading a column that is defined at DateTime and there are null values or empty strings?
1
6986
by: Jake | last post by:
Hi All, I have an object that ahs a property of time dateTime, this property is set to the contents of a DateTime field in the database(SQL Server). The problem I am haveing is that if the dataabase field is Null and the object property is set to the contense of that field. And I then assign the object proberty to the value of a control the control value is set to 01/01/0001
0
989
by: DotNetJunkies User | last post by:
I am using a DAL and i want to pass a date to another class, the date can be en normal date or null I send the date as an object, because datetime can't be null But when the date is saved in the database, i get the minvalue (1/01/1900) of the datertime and not null how can i put an empty date in the database? --- Posted using Wimdows.net NntpNews Component -
3
1049
by: hecsan07 | last post by:
How do I set a date field to null in C#? HS
7
2216
by: teddysnips | last post by:
Table DDL below: The tables I have contain Timesheet information. Each row in the tblTSCollected table contains an entry for an employee into the timesheet system, specifically by scanning the barcode on their badge. A whole bunch of business logic periodically attempts to "pair" these into logically matched scans. For example, some employees will scan in and out of a single place of work. For these there will be a row written to...
4
9771
by: John | last post by:
Hi, I'm writing a database programme with C# using a dataset. I want to set a DateTime for a particular field of a row to null (nulls are allowed for that column). When I use: newRow.Date_Pub=null; I get a compile error: "Cannot convert null to 'System.DateTime' because it is a value type". How do I set the field to null?
4
7197
by: shapper | last post by:
Hello, I have the following: DateTime c = database.Posts.Max(b =b.CreatedAt).Value; b.CreatedAt is of type "DateTime?" The problem is when database.Posts is empty. I get an error: Nullable object must have a value.
1
3199
pbala
by: pbala | last post by:
ConnectionString = "....." QueryString = "SELECT * FROM SomeTable" Dim myConnection As New MySql.Data.MySqlClient.MySqlConnection(ConnectionString) Dim myCommand As New MySql.Data.MySqlClient.MySqlCommand(QueryString, myConnection) Dim myReader As MySqlDataReader Try myConnection.Open() myReader = myCommand.ExecuteReader
0
9673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10443
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10216
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10002
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6783
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5565
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2921
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.