skip to Main Content
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.

4

Answers


  1. 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();
    
    Login or Signup to reply.
  2. 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();
    
    Login or Signup to reply.
  3. use this hope this will work

    DateTime.ParseExact(Textbox1.text, "MM/dd/yyyy", CultureInfo.InvariantCulture)
    
    Login or Signup to reply.
  4. Try the following way to validate the date

    bool res;
      DateTime Date;
      string myDate = Textbox1.text;
      res = DateTime.TryParse(myDate, out Date);
      if(res)
      {
       // Validation or conversion success and result will be available in Date variable
      }
      else 
      {
         // conversion Fail
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search