2010-11-11 52 views
3

我想从DataRow中的项目获取值,并且想将结果存储在可空日期字段中。从DataRow填充可空类型

我看到(在VB中)在对象System.Data.DataRowExtensions上显示共享的“字段”函数。下面是从对象浏览器:

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实例变量中引用它时,也没有在智能感知中列出的字段函数,我不希望这样做,因为函数是共享的。

昏暗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“功能无法识别。

EDIT

当从可空日期移动数据BACK键入一个数据行,我这是这样我做:

昏暗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类型吗?

..OR是否有一个内置的方便的功能来做到这一点,所以我不必定义我自己的?

回答

1

确保您已添加对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)的简写形式。

+0

我应该明白这一点。但我没有。谢谢。如何在相反的方向移动数据?这是处理空值的最简洁的方式吗? rowTest.Item(“MyDateTime”)= If(Me.MyDateTime.HasValue,CType(Me.MyDateTime,Object),DBNull.Value) – VJK 2010-11-11 21:44:47

+0

@VJK是的,如果你打算使用'DBNull.Value'你有什么是好的。使用'If(Me.MyDateTime.HasValue,Me.MyDateTime.Value,Nothing)'可能不是一个好主意,因为它将使用一个默认值,这可能不是您想要的类型。在这种情况下坚持'DBNull'。 – 2010-11-11 22:44:00