Click here to Skip to main content
14,486,704 members
Rate this:
Please Sign up or sign in to vote.
See more:
i'm trying to insert a data from date of birth txtbox to database but it shows a error cannot convert varchar to datetime

What I have tried:

registration button code
protected void Register_Click(object sender, EventArgs e)
{
btnSave_Click(dob.Text);
}


function btnsave_click code
public void btnSave_Click(string dob)
{
   cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "DateofBirth", DbType.String, dob));
}


and in my database i have declared dob as a datetime datatype.
above codes are only main codes
Posted
Updated 17-Mar-20 22:43pm
Rate this:
Please Sign up or sign in to vote.

Solution 1

Don't use text to pass a date to a DB: it relies on the user and the DB sharing a common culture, or the date may be misinterpretted. For example, is 01-02-03 1st Feb 2003 (Europe), 2nd Jan 2003 (USA), or 3rd Feb 2001 (ISO / Japan)?
Either use a Calendar control which provides a DateTime value directly, or use DatTime.TryParse to check and convert user input to DateTime, then pass the DateTime value to the DB directly via your parameter. Remember that users make mistakes when they enter anything and it's important to ensure that only valid inputs get to your DB.
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

Inside of method btnSave_Click, you need to:
1. Open SqlConnection[^]
2. Create SqlCommand[^]
3. Add parameters[^] to the command
4. ExecuteNonQuery[^]

As OriginalGriff already wrote, you need to use proper data type: DateTime, instead of text (string).
public void btnSave_Click(DateTime dob)
{
	int retVal = 0;
	using(SqlConnection connection = new SqlConnection("connection_string_here"))
	{
		connection.Open();
		using(SqlCommand cmd = new SqlCommand("command_text_here", connection))
		{
			cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "DateofBirth", DbType.DateTime, dob));
			retVal = cmd.ExecuteNonQuery();
		}
 	}
	if(retVal>0)
	{
		//success
	}
	else
	{
		//error!
	}
}
   
v2
Comments
phil.o 18-Mar-20 4:53am
   
DbType.DateTime would be more suitable, wouldn't it?
Maciej Los 18-Mar-20 6:02am
   
Thanks for pointing that out. Copy-paste mistake ;)
Member 14743579 18-Mar-20 6:07am
   
i have also used this.

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100