Home > Enterprise >  How do I fix Coversion failed when converting date and/or time from character string
How do I fix Coversion failed when converting date and/or time from character string

Time:06-02

con.open();
SqlCommamd comm = new SqlCommand("Insert into Debt_Tab values('" Textbox1.text "')",con);
comm.ExecuteNonQuery();

Textbox1 I is declared as a DateTime in my Sql table.

CodePudding user response:

There are a lot of different ways to format a date. To be sure that the database gets the correct format I suggest that you parse the date by specifying a culture.

For desktop applications, this is easy since the OS is configured for a specific format, while for web applications the user uses their own preferred format (unless you have specified something else).

To parse using the OS culture:

var date = DateTime.Parse(Textbox1.Text)

To parse using a specific culture:

var swedish = new CultureInfo("sv_se");
var date = DateTime.Parse(TextBox1.Text, swedish);

Another thing. There is something seriously wrong with your code. It's vulnerable to SQL injection attacks. You need to use a parameterized query instead.

var cmd = new SqlCommand(con);
cmd.CommandText = "Insert into Debt_Tab values(@date)";
cmd.Parameters.AddWithValue("date", date);
cmd.ExecuteNonQuery();

CodePudding user response:

Try this:-

Convert.ToDateTime()

example:-

con.open();
SqlCommamd comm = new SqlCommand("Insert into Debt_Tab values('"  Convert.ToDateTime(Textbox1.text).ToString("mm/dd/yyyy")  "')",con);
comm.ExecuteNonQuery();
  • Related