在System.Data.DataColumn.set_Item处:字符串未被识别为有效的DateTime

问题描述

我正在尝试执行以下操作并获取此异常

moDataTable.ImportRow(oDataSet.Tables(0).Rows(0))

  1. 在oDataSet.Tables(0)中,有一列名为“ date_created”的数据类型为“ string”
  2. moDataTable中的同一列“ date_created”具有数据类型“ DateTime”

我知道发生此错误的原因仅在于数据类型不同,但到上个月为止,相同的代码我有用,目前,相同的代码对我的所有同事和所有客户都有效。我正在尝试避免代码更改,因为它适用于所有其他代码,而这只是我系统的问题。我认为与系统相关的问题可以有人帮助我。也欢迎提供代码更改建议。但是首先要优先考虑系统特定​​的更改答案。

最短的代码如下

Public Sub ImportDataAddedThroughPopup(ByVal aoDaTarow As DaTarow,Optional ByVal abMakeFinal As Boolean = False)
            moDaTarow = aoDaTarow
            Dim oDataSet As New DataSet
            Dim oDataTable As New DataTable
            oDataTable = moDaTarow.Table.Clone
            oDataTable.ImportRow(moDaTarow)

            oDataSet.Tables.Add(oDataTable)  
            
            moDataTable.ImportRow(oDataSet.Tables(0).Rows(0)) 'At this line it's giving an error
            moDataTable.AcceptChanges()

End Sub

它引发的异常如下:

System.Data.DataColumn.set_Item中的

:未将字符串识别为有效的DateTime。无法将存储在date_created列中。预期的类型是DateTime。

System.FormatException:无法将字符串识别为有效的DateTime。

解决方法

我找到了,但是在系统中没有找到可以修复的特定错误,因此我决定进行代码更改,并按如下所示更改代码以解决此问题。 我确定oDataset.Tables(0)仅包含一行,所以我将数据类型为字符串的受影响的列“ date_created”替换为数据类型为DateTime的列“ date_created”

Public Sub ImportDataAddedThroughPopup(ByVal aoDataRow As DataRow,Optional ByVal abMakeFinal As Boolean = False)
        moDataRow = aoDataRow
        Dim newType = GetType(DateTime) 'Added code
        Dim dc As DataColumn = New DataColumn("DT_new",newType)    'Added code
        Dim oDataSet As New DataSet
        Dim oDataTable As New DataTable
        oDataTable = moDataRow.Table.Clone
        oDataTable.ImportRow(moDataRow)

        oDataSet.Tables.Add(oDataTable)  
        'Code block added [start]
         oDataSet.Tables(0).Columns.Add(dc)
         oDataSet.Tables(0).Rows(0)("DT_new") = FormatDateTime(moDataRow("date_created"),DateFormat.GeneralDate)
         oDataSet.Tables(0).Columns.Remove("date_created")
         dc.ColumnName = "date_created"
        'Code block added [End]
        
        moDataTable.ImportRow(oDataSet.Tables(0).Rows(0)) 'At this line it's giving an error
        moDataTable.AcceptChanges()

结束子