Click here to Skip to main content
15,890,043 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hi.

i have written an insert statement In VS2010 , in one of textbox which is for BirthDate , i have assigned Date type for it in SQlserver 2008r2,
and my code(parameter input) for that field is in below:

C#
cmd.Parameters.Add("@BirthDate_M", SqlDbType.Date).Value = Convert.ToDateTime(BirthDateTextBoxMilad.Text);


whenever i don't write any date inside textbox this exception appears:
String was not recognized as a valid DateTime.

while i want that whenever i don't write anything in textbox , Null to be inserted into the Database, so i wrote this code:
C#
cmd.Parameters.Add("@BirthDate_M", SqlDbType.Date).Value = null;


but if i do this , another exception will appear:
The parameterized query '(@FirstName nvarchar(5),@LastName nvarchar(5),@FatherName nvarch' expects the parameter '@BirthDate_M', which was not supplied.

which indicate that i have to insert a date.how can i prevent this happens and make it insert Null into the database.
Posted

hi,

try this,
C#
cmd.Parameters.Add("@BirthDate_M", SqlDbType.Date).Value = (BirthDateTextBoxMilad.Text.Trim()==string.empty) ? DbNull.value : Convert.ToDateTime(BirthDateTextBoxMilad.Text.Trim());


hope it works
 
Share this answer
 
Hi,
Try this:
C#
DateTime? value = Convert.ToDateTime(BirthDateTextBoxMilad.Text);
if (value.HasValue)
{
    cmd.Parameters.Add("@BirthDate_M", SqlDbType.Date).Value = value;
}



--Amit
 
Share this answer
 
try this

C#
cmd.Parameters.Add("@BirthDate_M", SqlDbType.Date).Value = DBNull.Value;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900