gpt4 book ai didi

vb.net - 从 DataRow 填充 Nullable 类型

转载 作者:行者123 更新时间:2023-12-02 06:43:24 25 4
gpt4 key购买 nike

我想从 DataRow 中的项目获取值,并将结果存储在可为 Null 的日期字段中。

我看到(在VB中)对象System.Data.DataRowExtensions上出现了共享“Field”函数。这是来自对象浏览器的:

Public Shared Function Field(Of T)(ByVal row As System.Data.DataRow, ByVal column As System.Data.DataColumn, ByVal version As System.Data.DataRowVersion) As T
Member of System.Data.DataRowExtensions
Summary:
Provides strongly-typed access to each of the column values in the specified row. The System.Data.DataRowExtensions.Field``1(System.Data.DataRow,System.Data.DataColumn,System.Data.DataRowVersion) method also supports nullable types.

Type parameters:
T: A generic parameter that specifies the return type of the column.

Parameters:
row: The input System.Data.DataRow, which acts as the this instance for the extension method.
column: The input System.Data.DataColumn object that specifies the column to return the value of.
version: A System.Data.DataRowVersion enumeration that specifies the version of the column value to return, such as Current or Original version.

但是,当我输入时

System.Data.DataRowExtensions.Field (...)

“...智能感知中无法识别字段。

当我尝试从 DataRow 实例变量引用 Field 函数时,它也没有在智能感知中列出,我不希望这是这样做的方法,因为该函数是共享的。

将 MyDataRow 调暗为 DataRow MyDataRow.Field()

我希望能够做这样的事情:

For Each MyDataRow As DataRow in ds.tables(0).rows
Dim nullableDate As System.Nullable(Of DateTime) = System.Data.DataRowExtensions.Field(Of System.Nullable(Of DateTime))("DateColInDb")
next

或者这个

For Each MyDataRow As DataRow in ds.tables(0).rows
Dim nullableDate As System.Nullable(Of DateTime) = MyDataRow .Field(Of System.Nullable(Of DateTime))("DateColInDb")
next

但是“System.Data.DataRowExtensions.Field”或“Field”函数无法识别。

编辑

当将数据从可为空日期类型移回数据行时,我这样做是这样的:

将 rowTest 调暗为 DataRow = dtbTest.NewRow

dtbTest.Rows.Add(rowTest)

rowTest.Item("MyDateTime") = Me.MyDateTime.ToObject

“ToObject”是我添加到 Nullable Date 数据类型的自定义函数。

模块 NullableDateExtensions

<System.Runtime.CompilerServices.Extension()> _
Public Function ToObject(ByVal thisDate As Date?) As Object
Return If(thisDate.HasValue, CType(thisDate, Object), DBNull.Value)
End Function

结束模块

评论?

是否有人有更好的方法将值移入数据行或从数据行移出为 Nullable 类型?

..或者是否有一个内置的方便函数可以执行此操作,这样我就不必定义自己的函数?

最佳答案

确保您已添加对 System.Data.DataSetExtensions.dll 的引用。转到解决方案资源管理器 -> 引用 -> 添加它。

然后这样使用:

For Each row As DataRow In ds.Tables(0).Rows
Dim nullableDate = row.Field(Of Nullable(Of DateTime))("DateColInDb")
Next

您还可以使用 DateTime? 的简写形式来代替 Nullable(Of DateTime)

关于vb.net - 从 DataRow 填充 Nullable 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4158568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com