Search code examples
vb6

How to fill a datepicker with value from database in VB 6.0?


I am working in VB6.0. I have this datepicker and I also have a datagridview. I am trying to make that when I click a column data enter in the textboxes and so with the datepicker to get the value of the date from the database

This is my code:

txtData.Value = dtmhs.Columns(3)

But I get the following error, any idea how to do it?

On database i declared the date as varchar because it had some problems with the date format yyyy/mm/dd and not dd/mm/yyy

Thank you in advance.


Solution

  • As @JoelCoehoorn pointed out: you're better off with storing dates in a date variable/column, both in your code and your database. It's very easy to achieve the desired formatting of a date using the Format$() function, i.e. create a String from a date with the formatting of your liking. The opposite however is prone to lots and lots of errors.

    Dim sMyDateAsString As String
    sMyDateAsString = Format$(dtmMyDateAsDate, "dd/mm/yyyy")
    

    As for setting the value of a DateTimePicker, again - with a date variable it's as simple as dtpMyDateTime.Value = dtmMyDateVariable.

    If you absolutely have to use any other variable type, IMHO the best approach is to set the individual date/time properties of the control, e.g.

    With dtpMyDateTime
       .Year = 2021
       .Month = 12
       .Day = 09
       ' Also set the time part, if needed...
       .Hour = 23
       .Minute = 58
       .Second = 0
       ' ... and now cue Iron Maiden's "Two minutes to midnight" ;-)
    End With
    

    Keep in mind, that these properties expect numeric values, so if you store your date in a 'String` variable, you have to convert those first. See, all that hassle with storing dates in strings...