【问题标题】:format dateTime in a datagridview bind to a bindinglist在 datagridview 中格式化 dateTime 绑定到绑定列表
【发布时间】:2018-06-28 14:45:53
【问题描述】:

我有: - 数据网格视图 - 绑定源 - 绑定列表

我将 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,我希望它通过 System.ComponentModel 类属性在类中已经计划的所有格式。

你有什么建议吗?

附:代码如下:

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

【问题讨论】:

  • 你是如何绑定datagridview的
  • 日期没有内在格式,所以不清楚你在问什么或者你实际上没有使用字符串 (all the format it's already planned in the class)
  • 当我运行代码时,在 datagridview 中,以“dd/mm/yyyy hh:MM”格式显示 myDate 单元格值,但我希望它显示为“hh:MM:ss” ,并且我不会从 datagridview.DefaultCellStyle.Format 属性设置日期格式,而是作为 myClass 中 myDate 属性的 ComponentModel 属性,正如我在代码中所示(使用 DataAnnotation.DisplayFormat 属性),但它没有不像我写的那样工作。
  • 为了使用数据注释,您必须使用一个可以查找它们的框架。 Windows 窗体数据绑定不是这样的框架。
  • 谢谢 jmcilhinney,你能给我解释一下这个概念吗?在此网页msdn.microsoft.com/en-us/library/… 上解释说 dataAnnotations 与 Framework 4.5 一起使用。我刚刚添加了对我的程序的引用。当您说“Windows 窗体数据绑定不是这样的框架”时,我不明白您的意思,您能帮我理解您的意思吗?

标签: c# vb.net datetime datagridview system.componentmodel


【解决方案1】:

我找到了解决方案(在 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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多