因此,我找到了这个线程,该线程恰好在谈论我的问题,但是该解决方案不适用于我:How to Change Format column in Datagridview to date type for this value
我有一个不同的数字模式,其中的数据是:YYMMDD,只有6个数字(000901-2000年9月1日)
将数据结构转换为数据字符串时,数据结构是否有所不同?是否需要采用初始格式?
这是我当前的代码字符串:
DataGridView1.Columns(1).DefaultCellStyle.Format = "yy/MM/dd"
只是试图获取任何格式,但它仍然保留为6位数字。
答案 0 :(得分:1)
经过一番思考和实验,我意识到了如何在GUI上而不是在加载数据时执行此操作。
您可以通过处理CellFormatting
的{{1}}事件来实现这种特殊格式。
我使用的测试数据:
DataGridView
DataGridView配置
Private Property MyData As DataTable
Private Sub InitialiseData()
MyData = New DataTable
MyData.Columns.Add("YMDString", GetType(String))
Dim dr As DataRow
dr = MyData.NewRow()
dr(0) = "000901"
MyData.Rows.Add(dr)
dr = MyData.NewRow()
dr(0) = "010901"
MyData.Rows.Add(dr)
dr = MyData.NewRow()
dr(0) = "020901"
MyData.Rows.Add(dr)
End Sub
还有Private Sub SetupDataGridView()
InitialiseData()
DataGridView1.AutoGenerateColumns = False
DataGridView1.Columns.Add("YMDString", "YMD String")
DataGridView1.Columns.Add("YMDDateTime", "YMD DateTime")
DataGridView1.Columns(0).DataPropertyName = "YMDString"
DataGridView1.Columns(1).DataPropertyName = "YMDString"
DataGridView1.DataSource = MyData
AddHandler DataGridView1.CellFormatting, AddressOf DataGridView1OnCellFormatting
End Sub
事件处理程序,可以完成艰苦的工作。 CellFormatting
解析不是您可以使用的最佳方法,但是它确实说明了您想要实现的原理。
DateTime
运行时,我得到以下结果:
答案 1 :(得分:1)
好的,尝试这个。将datagridview中的格式设置为要使用的日期格式。对于我的示例,我有3列,最右边的列包含6位数字的字符串。
在第三列中,我在datagridview中设置了yyyy / MM / dd格式。
在按钮中,单击“我遍历dgv”并将其解析为日期时间,以使该格式能够像现在使用日期类型一样工作。
For Each r As DataGridViewRow In DataGridView1.Rows
If Not r.IsNewRow Then
r.Cells(2).Value = DateTime.ParseExact(r.Cells(2).Value.ToString, "yyMMdd", CultureInfo.InvariantCulture)
End If
Next
点击按钮后,我得到了以下结果。
现在该列是日期数据类型,我们只需将格式和列格式更改为新的格式设置即可。
我添加了第二个按钮,并在该按钮中放置了代码
DataGridView1.Columns(2).DefaultCellStyle.Format = "MMM dd, yyyy"
立即将第三列更改为新格式
答案 2 :(得分:0)
我将您的六位数字符串转换为DateTime,然后按照您希望的格式进行格式化。
Dim strDate As String = "180211"
Dim myDate As New DateTime(CInt("20" & strDate.Substring(0, 2)), CInt(strDate.Substring(2, 2)), CInt(strDate.Substring(4)))
Debug.Print(myDate.ToString("yy/MM/dd"))
编辑: 我在VB.NET compare date time from string format
找到了一个更好的答案,感谢user1751825Dim myDate As Date = DateTime.ParseExact(strDate, "yyMMdd", CultureInfo.InvariantCulture)