c# - 格式化数据 GridView 中的日期时间绑定(bind)到绑定(bind)列表

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

我有: - 数据 GridView - 绑定(bind)源 - 绑定(bind)列表

我将 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 绑定(bind)到一个类,我希望它已经通过 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

最佳答案

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

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

关于c# - 格式化数据 GridView 中的日期时间绑定(bind)到绑定(bind)列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48339754/

相关文章:

python - pandas to_timedelta 忽略单位参数?

javascript - 如何在不使用整个日期的情况下仅将时间(类型为字符串)转换为 UTC 时间格式?

javascript - 将日期时间转换为本地时区 - Sugarcrm Moment js

c# - 函数主机未运行

vb.net - 做OR语句的更简单方法

javascript - 从 VB.NET 背后的代码调用点击事件或 JQuery 函数

c# - 动态运行 dotnet 代码的软件(或命令行)

c# - WPF FlowDocument - 绝对字符位置

c# - 工资列未在 Gridview 中更新

c# - 启动时运行后台任务