insert datetime into the database

windows

Guest
I want to insert datetime into the database.I want to insert date as a dd/MMMM/yyyy format

SqlDateTime x;
if((TextBox1.Text).Length==0)
{
x=SqlDateTime.Null;
}
else
{
x=DateTime.Parse(TextBox1.Text);
}
command=sqlConnection.CreateCommand();
command.CommandText="insert into Table2 values('"+x+"')";
sqlConnection.Open();
command.ExecuteNonQuery();
Response.Write("Save");

when I add this type of dates ex.25/02/2005 it occur error, how can I solve this.I change my code like this, now it works fine but I have small problem.
if my dropdowns SelectedIndex==0 then I wants to insert null value. I used for DBNull.Value, but it save as "01/01/1900" but I want to insert "<Null>" How can I do this?

string Mydate;

if(cboDateofBirth_Day.SelectedIndex!=0 && cboDateofBirth_Month.SelectedIndex!=0 && cboDateofBirth_Year.SelectedIndex!=0)
{
Mydate=cboDateofBirth_Day.SelectedValue+"/"+cboDateofBirth_Month.SelectedValue+"/"+cboDateofBirth_Year.SelectedValue;

}
else
{
Mydate=DBNull.Value.ToString();

}
command=sqlConnection.CreateCommand();
command.CommandText="set dateformat dmy;exec p_Insert_Test '"+Mydate+"' ";
sqlConnection.Open();
command.ExecuteNonQuery();
Response.Write("Save");I change my code like this, now it works fine but I have small problem.
if my dropdowns SelectedIndex==0 then I wants to insert null value. I used for DBNull.Value, but it save as "01/01/1900" but I want to insert "<Null>" How can I do this?

string Mydate;

if(cboDateofBirth_Day.SelectedIndex!=0 && cboDateofBirth_Month.SelectedIndex!=0 && cboDateofBirth_Year.SelectedIndex!=0)
{
Mydate=cboDateofBirth_Day.SelectedValue+"/"+cboDateofBirth_Month.SelectedValue+"/"+cboDateofBirth_Year.SelectedValue;

}
else
{
Mydate=DBNull.Value.ToString();

}
command=sqlConnection.CreateCommand();
command.CommandText="set dateformat dmy;exec p_Insert_Test '"+Mydate+"' ";
sqlConnection.Open();
command.ExecuteNonQuery();
Response.Write("Save");

there is no simple way that you can insert a null value into sql database from .net, the ony want you can do is, to use parameter, and then declare it as SqlDbType.DateTime, and then insert an empty SqlDateTime variable in to it..

take a look at this for example,

<!-- m --><a class="postlink" href="http://www.c-sharpcorner.com/Code/2003/Sept/EnterNullValuesForDateTime.asp">http://www.c-sharpcorner.com/Code/2003/ ... teTime.asp</a><!-- m -->
 
Back
Top