Home > database >  format string to a datetime in a datagrid vb.net
format string to a datetime in a datagrid vb.net

Time:04-27

    dg_datos.Columns.Add("tarea", "Tarea")
    dg_datos.Columns.Add("horas", "Horas")
    dg_datos.Columns.Add("descripcion", "Descripcion")
    dg_datos.Columns.Add("fecha", "Fecha")
    dg_datos.Columns("fecha").DefaultCellStyle.Format = "dd/MM/yyyy"


    dg_datos.Rows.Add("Ada Lovelace", "1", "desc.1", "10/11/2002")

I think I did not correctly specify the date format

CodePudding user response:

You don't format a String, as I already said. Just as numeric format specifiers only work on numbers, date format specifiers only work on Dates. The immediate fix is to use an actual Date:

dg_datos.Rows.Add("Ada Lovelace", "1", "desc.1", #11/10/2002#)

That is using a Date literal. Note that Date literals are ALWAYS in the format #M/dd/yyyy#. So I have switched the day and month values in your example. Now that you have an actual Date, date format specifiers will actually work.

You can get a Date value in various different ways. In places where you would use literals for Strings or numbers, you can use a Date literal too. If you want to construct a Date though, there are numerous ways. For example, you might use Date.Now for the current date and time, Date.Today to get the current date with the time zeroed. You can also use a constructor to build a Date from individual numbers for each component.

  • Related