[英]DataGridView DateTime column string was not recognized as a valid DateTime DataError
我有一個DataGridView
其中有一個DataTable
作為其DataSource
。 在DataTable
,我有一列的數據DataType
為DateTime
。 使用SqlDataAdapter
從SQL Server
成功填充了DataTable
。
我在用:
dgv.Columns(j).DefaultCellStyle.Format = "dd/MM/yyyy HHmm"
作為相關DataGridViewTextBoxColumn
的格式,數據可以正常加載並正確顯示為所需的格式。
但是,每當我對此列中的單元格之一進行有效(或無效)編輯時,總是會收到錯誤消息:
System.FormatException:字符串未被識別為有效的DateTime。 在System.DateTime.Parse(String s,IFormatProvider provider)處,請處理DataError事件。
我很驚訝,僅指定默認單元格樣式格式不足以使DataGridViewTextBoxColumn
正確確定用戶輸入的值。 所以,我的問題是:是否還有其他事件/地方可以(適當)指定某種CellValue = DateTime.TryParseExact(blah blah)
更正語句? 我當時想在CellValidating
, CellValidated
或DataError
事件中這樣做。 我會進行測試,但確實感覺好像我在這里缺少一個簡單的解決方案。
謝謝!
由於所需的格式是非標准格式,因此您必須提供解析和顯示邏輯的幫助。 一種方法是在CellFormatting
和CellParsing
事件中編寫一些代碼。
另一種方法是指定IFormatProvider
對象。 通常,這些只是進行格式化,您仍然可能需要代碼來進行解析,但是通過幾行額外的代碼, FormatProvider
也可以做到這一點:
Imports System.Globalization
Public Class DGVOddDateFormatter
Implements IFormatProvider, ICustomFormatter
Private myFmt As String = "dd/MM/yyyy HHmm"
Private mydgv As DataGridView
Private myNDX As Int32 = -1
Public Sub New(ctl As DataGridView, fmt As String, colNdx As Int32)
mydgv = ctl
myFmt = fmt
myNDX = colNdx
AddHandler mydgv.CellParsing, AddressOf dgv_CellParsing
mydgv.Columns(colNdx).DefaultCellStyle.Format = fmt
End Sub
Private Sub dgv_CellParsing(sender As Object, e As DataGridViewCellParsingEventArgs)
If e.ColumnIndex = myNDX Then
Dim dt As DateTime
If DateTime.TryParseExact(e.Value.ToString(),
myFmt, Nothing,
DateTimeStyles.None, dt) Then
e.Value = dt
e.ParsingApplied = True
End If
End If
End Sub
Public Function Format(format1 As String,
arg As Object,
formatProvider As IFormatProvider) As String _
Implements ICustomFormatter.Format
Dim dt As DateTime
If TypeOf (arg) Is DateTime Then
dt = CType(arg, DateTime)
Return dt.ToString(myFmt)
Else
Return "" ' or other default value
End If
End Function
Public Function GetFormat(formatType As Type) As Object Implements IFormatProvider.GetFormat
If TypeOf formatType Is ICustomFormatter Then
Return Me
End If
Return Nothing
End Function
End Class
創建格式化程序后,它將掛接到CellParsing
事件中,以提供補充邏輯以將內容轉換回有效的DateTime
。
dgv1.DataSource = dtSample
dgv1.Columns(4).DefaultCellStyle.FormatProvider = New DGVOddDateFormatter(dgv1,
"dd/MM/yyyy HHmm", 4)
如果沒有IFormatProvider
,則將在CellParsing
和CellFormatting
事件中使用相同的代碼,但必須在可能也使用奇數格式的其他網格上復制它。 由於格式化程序已傳遞要使用的格式,因此可以重用。
在這種情況下,DGV可以自己進行解析和格式化,因為它所需要的只是它所擁有的格式字符串。 但是在其他情況下,例如轉換紀元類型的日期(自某個任意日期以來的秒數),則毫無頭緒。 因此,它們為您提供了創建和使用自己的IFormatProvider
。 這些可以與Enum
轉換, TimeSpan
格式等其他功能一起使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.