从DataRow填充Nullable类型

时间:2010-11-11 19:41:46

标签: vb.net ado.net nullable

我想从DataRow中的项目中获取值,并且我希望将结果存储在Nullable Date字段中。

我看到(在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实例变量引用它时,Intellisense中也没有列出Field函数,我不希望这样做,因为函数是共享的。

Dim MyDataRow As 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”功能。

修改

将数据从Nullable Date类型BACK移动到数据行时,我就是这样:

Dim rowTest As 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类型吗?

..或者是否有一个内置的方便功能,所以我不必定义自己的?

1 个答案:

答案 0 :(得分:1)

确保您添加了对System.Data.DataSetExtensions.dll的引用。转到解决方案资源管理器 - &gt;参考文献 - &gt;加上它。

然后以这种方式使用它:

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

您还可以使用DateTime?的简写形式,而不是Nullable(Of DateTime)