Sunday, February 12, 2012

Cant insert NULL to DateTime field

Hi I'm using DetailView and I have a text box which show the date. I have formated the date as shortDate {0:d} format. I want to insert/update null if that text box is empty.

I have tried putting null value in my Update statement in sqlDataSource. And I'm getting error saying can't convert varchar to smalldatetime.

If I don't set null value as above, some large date (01/01/2033) has been inserted in my database.

Can anyone help me?

Moe

insert DBNull.Value not "null"

Hope this help|||Thanks a lot.. :)|||Dear,Can you explain where I put this code? I am newbie and have the same with formview, and I wonder where to enter this DBNULL?Can you help please?|||

Here is sample code:

sqlStmt ="insert into Emp (FirstName,LastName,Date) Values (?,?,?) ";conString ="Provider=sqloledb.1;user id=sa;pwd=;database=northwind;data source=localhost";cn =new OleDbConnection(conString);cmd =new OleDbCommand(sqlStmt, cn) ;cmd.Parameters.Add(new OleDbParameter("@.FirstName", OleDbType.VarChar, 40));cmd.Parameters.Add(new OleDbParameter("@.LastName", OleDbType.VarChar, 40));cmd.Parameters.Add(new OleDbParameter("@.Date", OleDbType.Date)); cmd.Parameters["@.FirstName"].Value = txtFirstName.Text;cmd.Parameters["@.LastName"].Value = txtLastName.Text;if ((txtDate.Text =="") ){cmd.Parameters["@.Date"].Value = DBNull.Value;}else{cmd.Parameters["@.Date"].Value = DateTime.Parse(txtDate.Text);}cn.Open();cmd.ExecuteNonQuery();Label1.Text ="Record Inserted Succesfully";

No comments:

Post a Comment