我试图在绑定之前检查数据行中是否存在列,但 column.contains 属性不起作用。不知道我在这里缺少什么。
这是代码:
Private Sub Bind(ByRef reader As SqlDataReader)
Dim dt As DataTable = reader.GetSchemaTable
list = New List(Of Employees)
For Each r As DataRow In dt.Rows
BindObject(r)
list.Add(obj)
Next
End Sub
Private Sub BindObject(ByRef dr As DataRow)
obj = New Employees
If dr.Table.Columns.Contains("ID") Then obj.VisitID = CType(dr("ID"), Integer)
End Sub
解决方案:
@ajakblackgoat 提供的以下解决方案绝对可以正常工作。
If dt.Select("ColumnName='ID'").Count = 1 Then obj.VisitID = CType(dr("ID"), Integer)
我提出了其他两种解决方案,它可能对其他人有所帮助。
替代解决方案一:
Dim dt As DataTable = reader.GetSchemaTable
Dim columns = New List(Of String)()
For i As Integer = 0 To reader.FieldCount - 1
columns.Add(reader.GetName(i))
Next
If columns.Contains("ID") Then obj.ID = CType(dr("ID"), Integer)
替代解决方案二:
Dim dt As New DataTable
dt.Load(reader)
If dr.Table.Columns.Contains("ID") Then obj.VisitID = CType(dr("ID"), Integer)