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

Asked

Viewed 325 times

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();
  }
}

Wanted the format that the user write in Textbox were this:

2017-09-26 11:24:39.693

When I write this value on textbox and clicking on the button generates this error: Converting a data type nvarchar in a data type datetime resulted in a value outside the range.

How do I fix it?

Another question, how can I make one 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 code above?

1 answer

0


Convert your text to a format datetime in this way

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

To set a Datetimepicker for a format specific, 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

DateTimePicker Properties

  • The converter gave this error: cannot convert from "System.Globalization.Cultureinfo" to "System.Globalization.Datetimestyles Already the Datetimepicker, where can I use this code?

  • 1

    @Viniciusbittencourt now try the new code to convert, and where to edit this in the reply.. but as for the code you could insert in Load for example but the best way is to define in the same properties!

  • It worked, but I wanted to have Milisegundos in the format, how would it look? And how can I select the time in Datatimepicker or has no way?

  • @Viniciusbittencourt this link https://msdn.microsoft.com/pt-br/library/8kb3ddd4(v=vs.110). aspx shows the possibilities of date/time format but my machine did not work milliseconds, and the time needs to change the setting 'Format' to custom, you will be able to choose the time in the datetimepicker itself

  • There is no way to change the time in the Datetimepicker?

  • @Viniciusbittencourt has yes, but not by the option of the calendar, only typing!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.