Insert date written in the textbox in a certain format for the database

0

Code:

private void button1_Click(object sender, EventArgs e)
{
  conn.Open();
  using (SqlCommand cmd = new SqlCommand("INSERT INTO (StartDate) 
  VALUES(@StartDate)", conn))
  {                                  
    cmd.Parameters.AddWithValue("@StartDate", txtStartDate.Text);
    cmd.ExecuteNonQuery();
  }
}

I wanted the format the user wrote in TextBox to be this:

  

2017-09-26 11: 24: 39,693

When I write this value in the textbox and click the button it generates this error: The conversion of a data type nvarchar into a data type datetime in> resulted in a value out of range.

How do I fix it?

Another question, how can I make a DateTimePicker in this format:

  

2017-09-26 11: 24: 39,693

And send it to the database when you click the button, same as the above code?

    
asked by anonymous 26.09.2017 / 17:00

1 answer

0

Convert your text to a dateTime format this way

cmd.Parameters.AddWithValue("@StartDate", DateTime.ParseExact(txtStartDate.Text, "yyyy-MM-dd HH:mm:ss", null););

To set a DateTimePicker to a format , just use the following code:

seuDateTimePicker.CustomFormat = "yyyy-MM-dd HH:mm:ss"

where the format you want would be "yyyy-MM-dd HH: mm: ss"

or the format can be changed directly in the CustomFormat property of DateTimePicker

    
26.09.2017 / 17:19