首页 > 解决方案 > 以自定义格式格式化 DataGridView 列中的日期

问题描述

我有一个DataGridView,用户在其中插入有关不同产品的数据。其中一列保存项目到期日期的数据。有人告诉我要让用户输入这个日期变得简单快捷,所以我必须将日期格式设置为:“ddMMyy”(日、月和年之间没有点或斜线分隔符,只有 2 位数字年)。DataGrid 绑定到我的DataBase,所以我想我应该在对 DataBase 进行更新之前将用户输入转换为 DataBase 的可接受格式(“dd.MM.yyyy”)。

但是,我尝试在CellLeave 事件中进行此更新,因为它是用户离开单元格时调用的第一个事件。它没有用,在CellEndEditCellValidatingCellValidate中尝试过,仍然没有成功(DataTable 中的更新是在CellValidate事件中进行的)。我尝试了以下代码,但在断点上,我似乎没有格式化 DataGrid 中的实际文本,而是数据库中已经存在的旧值:

If dgv.CurrentCell.ColumnIndex = dgv.Columns("Expiry_Date").Index Then
        Dim strData As String = dgv.Rows(e.RowIndex).Cells(e.ColumnIndex).Value.ToString()
        Dim day As String = strData.Substring(0, 2)
        Dim month As String = strData.Substring(2, 2)
        Dim year As String = strData.Substring(4, 2)
        strData = day & "." & month & "." & year
        Dim d As Date = Date.Parse(strData)
        dgv.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = d
End If

插入DataGridView单元格的值是“160420”,本来应该格式化为“16.04.2020”,但是strData显示的是“20.09.2021”,这是旧值,是编辑前数据库中的值.

我知道我可能会错过一些实际上很容易的事情,但到目前为止我还没有设法解决这个问题。虽然我提供的代码是 VB.NET,但也感谢任何 C# 帮助,因为我可以轻松地在这两者之间进行转换。

标签: c#vb.netdatagridviewdate-formatsql-update

解决方案


这似乎有效:

Imports System.Globalization

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim table As New DataTable

        With table.Columns
            .Add("ID", GetType(Integer)).AutoIncrement = True
            .Add("Name", GetType(String))
            .Add("Date", GetType(Date)).AllowDBNull = True
        End With

        With table.Rows
            .Add(1, "Peter", #1/1/2000#)
            .Add(2, "Paul", #6/19/1969#)
            .Add(3, "Peter", Date.Today)
        End With

        DataGridView1.DataSource = table

        'Use the display format by default.
        DataGridView1.Columns(2).DefaultCellStyle.Format = "dd.MM.yyyy"
    End Sub

    Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
        If DataGridView1.CurrentCellAddress.X = 2 Then
            'Display the date in the editing format.
            Dim cellValue = DataGridView1.CurrentCell.Value
            Dim text = If(cellValue Is DBNull.Value, String.Empty, CDate(cellValue).ToString("ddMMyy"))

            e.Control.Text = text
        End If
    End Sub

    Private Sub DataGridView1_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
        If e.ColumnIndex = 2 AndAlso
           DataGridView1.EditingControl IsNot Nothing AndAlso
           Not e.FormattedValue.Equals(String.Empty) Then
            Dim value As Date

            'Validate the input using the editing format and the display format.
            e.Cancel = Not Date.TryParseExact(CStr(e.FormattedValue),
                                              {"ddMMyy", "dd.MM.yyyy"},
                                              Nothing,
                                              DateTimeStyles.None,
                                              value)

            If Not e.Cancel Then
                'Ensure data is displayed using the display format.
                DataGridView1.EditingControl.Text = value.ToString("dd.MM.yyyy")
            End If
        End If
    End Sub

End Class

当编辑会话开始时,编辑控件中的文本被显式格式化为“ddMMyy”,如果输入通过验证,文本将转换回“dd.MM.yyyy”格式,以便网格自动将其解析回来到一个Date


推荐阅读