SQL datetime field

DateTime dt = Convert.ToDateTime(dtlabel.Text); 

string DT = dt.ToString("MM/dd/yyyy hh:mm:ss");

When I insert  string in database everything work fine but if string is empty I have this 1.1.1900 0:00:00 can I change this to Null or blank



4/15/2009 7:54:19 AM
asp.net.getting-started 91979 articles. 4 followers. Follow

7 Replies

Similar Articles

[PageSpeed] 32

instead of declaring the string like this

string DT = dt.ToString("MM/dd/yyyy hh:mm:ss");

declare the string string DT = string.Empty;

And befor assigning the value to string check for null value.



DateTime dt = Convert.ToDateTime(dtlabel.Text);

 DT = dt.ToString("MM/dd/yyyy hh:mm:ss");


Anil Kumar
4/15/2009 8:05:38 AM

I have string.empty, i don't have problem with insert or any problem, I want to know how change 1.1.1900 to word Null.


4/15/2009 8:10:24 AM

 Set the Default value or Binding for the field to NULL (database, table, field datetime) so if there is not data it will write a NULL.

When you ask a question, remember to click "Mark As Answer" when you get a reply which answers your question.
4/15/2009 8:10:53 AM

What does your code look like for the insert? I would advise you to switch to using SqlParameters unless you already do so (and avoid concatenating the values of the insert statement).


SqlCommand cmd = new SqlCommand("INSERT INTO SomeTable (Name, [Date]) VALUES (@Name, @Date)", conn);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
if (!string.IsNullOrEmpty(dtlabel.Text))
   cmd.Parameters.AddWithValue("@Date", Convert.ToDateTime(dtlabel.Text));
   cmd.Parameters.AddWithValue("@Date", SqlDateTime.Null);

The key thing here is to use SqlDateTime.Null to correctly insert a NULL value into a DateTime column. And by checking IsNullOrEmpty on the string, you don't have to convert it to 1900.1.1.

If this post was useful to you, please mark it as answer. Thank you!
4/15/2009 8:10:54 AM

make default value from sql server to any thing you want

Mostafa Issa Issa

MSTC ,.NET Developer
LINKdotNET - LINK Development

Don't forget to Mark As Answer on the post that helped you. It encourages them to share their knowledge, and it helps others to easily identify the solution.
4/15/2009 8:12:25 AM

This should check the DateTime value and set DT to either null or your string date value. 

   DateTime dt = Convert.ToDateTime(dtlabel.Text);
   string DT = dt.Equals(DateTime.MinValue) ? null : dt.ToString("MM/dd/yyyy hh:mm:ss");

4/15/2009 8:15:05 AM

Thanks Kulrom!

4/15/2009 8:24:25 AM

Similar Artilces:

Free .Net and Sql Server Training Videos for Developers just getting started
I figured since this is the Getting started forum I would mention a great .Net training video site with some free videos.http://www.TechnicalVideos.netThanksMike James...

.NET DateTime and SQL Server DateTime problem
.NET DateTime and SQL Server DateTime problem  I have the following if statement in an SQL stored procedure: IF (@Image = 1 AND @DateTimeUploaded = (SELECT ImageMainDateTime FROM Images WHERE UserID = @UserID))   The value of the @DateTimeUpdated variable was taken from the ImageMainDateTime field when the data was requested by a ASP.NET webpage and is passed back here when that page is submitted so I can compare what the DateTime was when the data was requested with what it is now, in other words I’m doing a concurrency check (I can’t use TimeStamp for many reasons, ...

DateTime unable to save in datetime field of SQL database
 Hi all, having a little problem with saving dates to sql databaseI've got the CreatedOn field in the table set to datetime type, but every time i try and run it i get an error kicked up  Error "The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.The statement has been terminated."I've tried researching it but not been able to find something similar.  Heres the code: DateTime createOn = DateTime.Now;string sSQLStatement = "INSERT INTO Index (Name, Description, Creator,CreatedOn) values ('" + name + "','" + descri...

Compating DateTime field from sql table to DateTime Object
Hi. I have a SQL query that suppose to compare a given DateTime object to a datetime type coloumn : SELECT COUNT(*) FROM [QuestionnairesData] WHERE [SQClientUsername] = '" + Profile.UserName + "' AND [FillingDate] > " + Report.GetLastProductionReportDate(sqClient.SQCLIENTID)  the problem i get is on the last part of the select query. the DateTime object Report.GetLastProductionReportDate(sqClient.SQCLIENTID) gives me : 2/14/2007 15:49:04 PM and when i delete the time part it works well but i need to check for both date and time in this case. there is some issues with DateTime o...

Convert .NET DateTime format to SQL DateTime format
Hi!!I'd like to know if there is a function to convert the DateTime format used in C# (VS2005) : dd/mm/yyyy HH:mm:ss to the format used in SQL Databases: yyyymmdd HH:mm:ssThanks folks!...

Getting Start With .net
hi i'm intersted to learn asp.net (vb or delphi) . i programming with delphi6 but i'd like to tp know something about programming in internet specially with .net . i hear about microsoft.net with delphi 7 that i can programming with delphi in .net .... is it right ? what 's our opinian about it ? and better to learn Vb.Net or continu with delphi(or delphi.net) thanks. Ali Darabian I think there is some support for Delphi in .Net. However, you will find much more support from the user community if you choose a more popular language such as VB.Net or C#. Since your al...

how to get start with .NET
the net help people installed  to my desktop 1-microsoft visual studio .NET enterprise developer 2003 2-microsoft .NET framework 1.1 what else do i need ...???  and how can i try with some simple code in VS.Net and run it to see wat happen...????? please help If you want to develope web applications, then you'll also need IIS on your PC.  That'll require XP-Professional or Windows 2000/2003, but XP-Home edition won't allow IIS installation. As for how to get started, you can search the web for some tutorials or buy a good book on VS.  The topic is way too vast to...

How can I update an MS SQL 7.0 datetime field with embedded sql
I have a datetime field in MS Sql 7.0 named Revised_Date. I can update this date with my datawindow but I can't update it with embedded sql. I have tried the following which doesn't work UPDATE dbo.employees SET revised_date = date() ; produces invalid function error UPDATE dbo.employees SET revised_date = 2000-07-31 ; which yeilds 05/17/05 which is incorrect date ld_date time ldt_datetime ld_date = today ldt_date = datetime(ld_date) UPDATE dbo.employees SET revised_date = :ldt_date; which yields error How can I accomplish this ? T...

convert an sql datetime column to .net datetime data type in front end...?
I have a field (ldate) in a table that typically displays data in the following format:2007-11-12 20:30:47.000In the front end I want the time and the date separately. But as I try to cast it to a datetime object it is giving me a System.NullReferenceException. What I tried to do was just this: Protected Sub gvTopics_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvTopics.RowDataBound Dim img As Image = gvTopics.FindControl("imgIcon") Dim lbDate, lbTime As Label lbDate = gvTopics.FindControl(...

HOW DO I: Insert nulls into SQL dateTime field stored in SQL DB from a web UI textbox
I’m looking for feedback on the Best/Right way to Insert nulls into SQL dateTime field in SQL DB from a web UI textbox.    Option 1:     Presently implemented:  Dim dtFollowUpDate = IIf(dtDateFollowUp.Text = "", System.Data.SqlTypes.SqlDateTime.Null, dtDateFollowUp.Text) Although ithis does what is needed it generates the following inner exception   ParamValue    {System.Data.SqlTypes.SqlDateTime} Object[System.Data.SqlTypes.SqlDateTime] {System.Data.SqlTypes.SqlDateTime}          ...

Where to start and how did you get started?
Hi, I have had a feeling for a long time to jump into the adds market for some time due to my low income (shooting for the stars) and I don't have anything better to do these days. But I find it really difficult not to give up due to lack of guides (what I can find atleast) and all the hard words which only makes me confused. But I won't give up. Never. Not sure if this is the right place to post this, but I deffinitly would be really greatfull for help getting started. How did you get started? +If there are any teacher that wanna show me the ropes private, I can give payment with ...

Get SQL Error from .Net
I am sing SQL Procedures for Insert and Update. In the SQL Procedure i used try catch.  How can i get the SQL exception from .net. Try{ //Execute your sql here.}Catch  (SqlException and sqlEx){ //Do Something}   Pushing out shapes, to a popular beat combo. If you want to cause an error in the calling application you need to raise an error in the Catch Block.  If you just want to return the error information as a resultset, execute a select statement.  There are several variables, only available in the Catch Block, that you can use to ret...

linking a sql field to point to the value of another sql field
is it possible to create hyperlinks in powerbuilder such that if you retrieve two fields from a database.. and want to display the first field on the screen and have it link to the value of the other field (when clicked) which is actually a URL address, you can? any help will be appreciated. thank you! ...

Working with DATETIME Fields in SQL
I'm trying to delete data older than 24 hours from a particular table. Below is my SQL. It runs successfully but does not delete data. What is wrong with the syntax? delete from IBLM$OPERATIONLOG FU where FU.datetime = 'now' - (24/60) Robin, Your WHERE condition seems to only evaluate to true those records which contain FU.datetime equal to the expression result. It won't select records older than that. Perhaps you can change it to... delete from IBLM$OPERATIONLOG FU where FU.datetime < 'now' - (24/60) OR... delete from IBLM$OPERATIONLOG...

Web resources about - SQL datetime field - asp.net.getting-started

Is there a JQuery plugin to convert UTC datetimes to local user timezone?
If I have a tag: &lt;span class="utctime"&gt;2010-01-01 11:30 PM&lt;/span&gt; I would like a jquery script or plug in to convert every utctime ...

Targetprocess 3.7.3: Epic unit for Bug/Story cards, new DateTime functions in Webhook plugin
Webhook plugin supports new DateTime functions AddDays(DateTime date, int days) – Returns a new date with the number of days added. The number ...

Common Pitfalls when working with DateTime’s
In .NET, the DateTime structure provides us wonderful functionality, but this seemingly simple structure can cause a lot of headaches if you ...

Parsing Twitter Date format to .Net DateTime
Recently when I needed to parse the twitter datetime format into a .Net DateTime I found this post on the web showing how to do it. However, ...

C Sharp (programming language) - Wikipedia, the free encyclopedia
(pronounced see sharp ) is a multi-paradigm programming language encompassing strong typing , imperative , declarative , functional , generic ...

1753 - Wikipedia, the free encyclopedia
Language: English Afrikaans አማርኛ العربية Aragonés Asturianu Aymar aru Azərbaycanca বাংলা Bân-lâm-gú Basa Banyumasan Беларуская ‪Беларуская (тарашкевіца)‬ ...

Coded Smorgasbord: Schizophrenic Haiku Comments and More
... writes Malcom StandardResponse UnSubscribeNewsletterUserAccount( string opTinGUID,string email, string sellingRegion, string source, DateTime ...

Limburg.be - Welkom op de site van de provincie Limburg - Welkom_op_de_site_van_de_provincie_Limburg
visit wonen werken leven ontspannen infopunt home op trefwoord contactpersonen wegwijs sitemap print deze pagina Je bent hier: limburg.be Contact ...

Simples Ideias. Por Nando Vieira.
Simples Ideias Siga-me no Twitter Junho/2012 Usando o Vagrant como ambiente de desenvolvimento no Windows http://simplesideias.com.br/usando ...

Resources last updated: 1/21/2016 2:14:26 AM