Hi,
I am loading the user entered data from the form to sql database.
Here is my code:
SqlConnection con = new SqlConnection("bla bla");
con.Open();
string insertsql = "insert into John (date1, date2, date3)" + "values ('" " "', '" + maskedTextBox1.Text + "', '" + maskedTextBox2.Text + "', '" + maskedTextBox3.Text +"');";
SqlCommand insertcmd = new SqlCommand(insertsql, con);
insertcmd.ExecuteNonQuery();
con.close();
All masked textboxes are in date format only.
My question is:
If i dont enter the date on the form in masked textboxes, i am getting error.
How can i enter null values in database.
Darma
Loading
EhteshamPosted May 22, 2012, 7:18 AM
2) change your code to
SqlConnection con = new SqlConnection("bla bla");
con.Open();
DateTime DtParsedDate=new DateTime();
string insertsql = "insert into John (date1, date2, date3)" + "values ('" " "', '" + (DateTime.TryParse(maskedTextBox1.Text, out DtParsedDate)==true?DtParsedDate:null) + "', '" + maskedTextBox2.Text + "', '" + maskedTextBox3.Text +"');";
SqlCommand insertcmd = new SqlCommand(insertsql, con);
insertcmd.ExecuteNonQuery();
con.close()
Hope this helps
EhteshamPosted May 22, 2012, 8:55 AM
consider the below example
DateTime DtParsedDate = new DateTime();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into Table(Col1) values(@Col1)";
cmd.connection=con;
if (DateTime.TryParse(masktextbox1.text, out DtParsedDate))
cmd.Parameters.Add(new SqlParameter { ParameterName = "@Col1", SqlDbType = SqlDbType.DateTime, IsNullable = true, Value = DtParsedDate });
else
cmd.Parameters.Add(new SqlParameter { ParameterName = "@Col1", SqlDbType = SqlDbType.DateTime, IsNullable = true, Value = DBNull.Value });
cmd.executenonquery();
or
do not include the column name in insert query if DateTime.TryParse returns false you dont specifiy the value for a column it will take null
if masktextbox1.text tryparse returns false dont assign that mask
textbox1 value to column
darma tejaPosted May 22, 2012, 8:31 AM
I changed the code as following and it is working now.
(DateTime.TryParse(maskedTextBox1.Text, out DtParsedDate)==true?Convert.ToDateTime(DtParsedDate):Convert.ToDateTime(null))
When i dont enter any date, The default date shows in my datbase is 0001-01-01.
But i dont want to show any date like 0001-01-01.
I want to show only null
How can i do
Thanks
EhteshamPosted May 22, 2012, 8:10 AM
darma tejaPosted May 22, 2012, 7:46 AM
Thanks for fast reply and the code.
But i am getting error at ?DtParsedDate:null)
Darma