繁体   English   中英

将datagridview中的dateTime格式绑定到绑定列表

[英]format dateTime in a datagridview bind to a bindinglist

我已经:-Datagridview-BindingSource-BindingList

我将BindingList关联到包含dateTime属性的类。 datagridview将值显示为“ dd / mm / yy hh:MM”。 我想格式化为“ hh:MM:ss”。

我知道有一种设置列的模式:

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

但是我想知道是否有其他方法可以做到这一点,特别是在两种情况下:1)设置我想到的System.ComponentModel属性

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

但它不起作用。

2)将Datagridview中的所有dateTime列都设置为'DefaultCellStyle.Format =“ t”但是我不太喜欢这种解决方案,因为datagridview绑定到了Class,我希望它已经具有所有格式通过System.ComponentModel类的属性在类中计划。

您有什么建议吗?

PS这里的代码:

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

我在MSDN网页上找到了解决方案。

如本网页所述

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

解决方案可能是处理CellFormatting事件,如msdn此处https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellformatting.aspx所述

因此在代码中:

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

但我认为一个更好的解决方案是:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM