我有: - 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类属性计划在类中 .
你有什么建议吗?
附:这里的代码:
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 回答
我找到了一个解决方案(在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
所以在代码中:
但我认为这是一个更好的解决方案:
为默认格式,处理dataGridView ColumnAdded事件(https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columnadded(v=vs.110).aspx)(因此在添加列时,它只进行一次格式化) .
和单个单元格'in running'的格式化,可能是
处理了CellFormatting事件 .