Search code examples
vb.netdatetimedatetimepickersqlyog

String was not recognized as a valid DateTime Error when try to sow date and time data into DateTimePicker from DataGridView


I want to display Date and time (format: dd/MM/yyyy h:mm tt) from column "DateTime to DateTimePicker. but it shows an error String was not recognized as a valid DateTime.

Private Sub dgvSchedule_RowEnter(sender As Object, e As DataGridViewCellEventArgs) Handles dgvSchedule.RowEnter
        'DISPLAYS COLUMN VALUE IN TEXTBOXES
        If e.RowIndex >= 0 Then
            Dim row As DataGridViewRow
            row = Me.dgvSchedule.Rows(e.RowIndex)
            txtID.Text = row.Cells("Patient_ID_Number").Value.ToString

            dtpDate.Text = row.Cells("Date_Time").Value 'THIS IS WHERE THE ERROR OCCUR

            txtFirstname.Text = row.Cells("Firstname").Value.ToString
            txtLastname.Text = row.Cells("Lastname").Value.ToString
            txtPhoneNumber.Text = row.Cells("Phone_Number").Value.ToString
        End If
    End Sub

Solution

  • What is the format of your 'Date_Time' column?

    If it's a MySQL datetime like this: 2016-01-23 23:30:55 then you can just use the DateTime.Parse of VB.NET

    Dim new_date As DateTime = DateTime.Parse("2016-01-23 23:30:55")
    DateTimePicker1.Value = new_date
    

    Note that the format is 'Custom' and the CustomFormat is dd/MM/yyyy h:mm tt

    DateTimePicker1.Format = DateTimePickerFormat.Custom
    DateTimePicker1.CustomFormat = "dd/MM/yyyy h:mm tt"
    

    So the final code could be:

     DateTimePicker1.Format = DateTimePickerFormat.Custom
     DateTimePicker1.CustomFormat = "dd/MM/yyyy h:mm tt"
    
     Dim new_date As DateTime = DateTime.Parse(row.Cells("Date_Time").Value.ToString())
     DateTimePicker1.Value = new_date
    

    I also noticed that you are using:

    dtpDate.Text = row.Cells("Date_Time").Value
    

    instead of

    dtpDate.Value = row.Cells("Date_Time").Value
    

    Note that these are different: Text and Value.