Click here to Skip to main content
15,893,508 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
C#
protected void Register_Click(object sender, EventArgs e)
{
btnSave_Click(dob.Text);
}


function btnsave_click code
C#
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

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.
 
Share this answer
 
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).
C#
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!
	}
}
 
Share this answer
 
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900