seun
seun

Reputation: 37

Converting data entered by user to date

I'm trying to insert data of type 'date' from a textbox on my form to the database.

I want to ensure data entered by the user is stored in the format'dd/mm/yyyy' in the database. I have a column in the database of type 'date' but when i enter values of the format above, i get an exception (something like: cannot implicitly convert varchar to type date).

Please how do I convert date entered to the format 'dd/mm/yyyy'. I tried using CONVERT((varchar,getdate(),103) AS [DD/MM/YYYY]) but i cant figure out where to place it in my code. I'm new to c# and sql server, help please!!

Upvotes: 0

Views: 77

Answers (2)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

use parameterised queries:

DateTime dt;
dt = DateTime.ParseExact(TextBox1.Text,
        "dd/MM/yyyy",CultureInfo.InvariantCulture);

SqlCOnnection con=new SqlConnection("/*connection string here*/");
string query = "INSERT INTO [TABLENAME](DateCol) VALUES(@DateValue)";
SqlCommand cmd=new SqlCommand(query,con);
cmd.Parameters.AddWithValue("@DateValue",dt);
con.Open(); 
cmd.ExecuteNonQuery();

EDIT: from your comments :

i want the date to also be displayed in the same 'dd/MM/yyyy' format in the database

You can can not control underlying Database how it displays or manages your Date in Database but if you want to get the date in format of dd/MM/yyyy while reading from database you can try the below:

SqlCOnnection con=new SqlConnection("/*connection string here*/");
string query = "SELECT [DateCol] FROM TABLENAME]";
SqlCommand cmd=new SqlCommand(query,con);

con.Open(); 
SqlReader reader = cmd.ExecuteReader();
while(reader.Read())
{
   DateTime dt= Convert.ToDateTime(reader["DateCol"].ToString());
   string mydateString = dt.ToString("dd/MM/yyyy");
}
con.Close();

Upvotes: 1

Carl Sargunar
Carl Sargunar

Reputation: 587

It's better to not convert the date in SQL, and just pass it back as a date, and then within C# you can structure it however you want

myDate.ToString("dd/mm/yyyy")

Upvotes: 1

Related Questions