You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DataGridView第10列日期格式化为yyyy-MM-dd?VB代码未生效

解决DataGridView日期格式修改问题

你的代码没生效是因为错误访问了单元格Value的DefaultCellStyle属性——Cells(10).Value是单元格的内容值,它本身没有DefaultCellStyle这个属性,正确操作应该是直接设置列的默认样式或者单元格的样式;另外注意DataGridView的列索引从0开始,你说的第10列对应的索引是9,之前的索引也可能搞错了。

给你两种可行的解决方法:

方法一:直接设置整列格式(推荐,效率更高)

不用遍历每一行,直接给目标列设置默认格式,所有单元格都会自动应用:

DataGridView.Columns(9).DefaultCellStyle.Format = "yyyy-MM-dd"

方法二:遍历单元格设置(针对特定行需求)

如果只需要给部分行设置格式,可以遍历行操作单元格的Style:

For i = 0 To DataGridView.Rows.Count - 1
    DataGridView.Rows(i).Cells(9).Style.Format = "yyyy-MM-dd"
Next

额外注意:如果单元格内容是字符串类型

如果你的单元格值不是DateTime类型,而是带T的字符串(比如接口返回的原始字符串),直接设置格式不会生效,需要先把字符串转成DateTime再赋值:

For i = 0 To DataGridView.Rows.Count - 1
    Dim dateStr As String = DataGridView.Rows(i).Cells(9).Value.ToString()
    Dim dt As DateTime
    ' 尝试解析字符串为DateTime
    If DateTime.TryParse(dateStr, dt) Then
        DataGridView.Rows(i).Cells(9).Value = dt
        DataGridView.Rows(i).Cells(9).Style.Format = "yyyy-MM-dd"
    End If
Next

内容的提问来源于stack exchange,提问作者fooof20002

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 14:00:54