format dateTime in a datagridview bind to a bindinglist

1.3k Views Asked by At

i've: - Datagridview - BindingSource - BindingList

I associate the BindingList to a class that contain a dateTime property. The datagridview show the value as 'dd/mm/yy hh:MM'. I want to format as 'hh:MM:ss'.

I know that there is a mode to set the column:

dataGridView1.Columns["yourColumnName"].DefaultCellStyle.Format = "t"

But i was wondering if there is a different way to do that, in particular in two ways: 1) set a System.ComponentModel Attribute I thought of

<System.ComponentModel.DataAnnotation.DisplayFormat(ApplyFormatInEditMode:= True, DataFormatString:= "{hh:MM:ss}")>

but it don't works.

2) set all the dateTime columns in the Datagridview as 'DefaultCellStyle.Format = "t" But i don't like so much this solution, because the datagridview it's bind to a Class, and i'd like that all the format it's already planned in the class throught the System.ComponentModel class attributes.

Do you have any advices?

P.S. Here the code:

Public dataGridView1 As New DataGridView
Public bs as New BindingSource
Public bl as New BindingList(Of MyClass)

...

bs.DataSource = bl
dataGridView1.DataSource = bs

...

Public Class myClass
  Sub New()
    bl.Add(ME)
  End Sub

  <System.ComponentModel.Browsable(True)>
  <System.ComponentModel.DataAnnotations.DisplayFormat(ApplyFormatInEditMode:=True, DataFormatString:= "hh:MM:ss")>
  Public Property myDate As DateTime
End Class
1

There are 1 best solutions below

0
Marcello On

i've found a solution (on MSDN webpage).

As explained at this webpage

http://dailydotnettips.com/2011/02/05/how-to-change-gridview-column-alignments-for-dynamic-data-source/

A solution could be handling the CellFormatting event, as explained at msdn here https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellformatting.aspx

So in code:

Private Sub dataGridView1_CellFormatting(ByVal Sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles dataGridView1.CellFormatting
    With dataGridView1.Columns(e.ColumnIndex)
        'you can format just a column referring to the name of the property which with is binded'
        Select Case .Name
            Case "the_Name_Of_The_Property_Binded"
                e.CellStyle.Format = "hh:MM:ss"
        End Select
        'or you can format all the columns that are associated with a DateTime Property'
        If .ValueType = GetType(DateTime) Then
            e.CellStyle.Format = "hh:MM:ss"
        End If
    End With
End Sub

But i think a better solution it's: