user1263981
user1263981

Reputation: 3147

How to check if column exists in the Datarow

I am trying to check if column exists in the datarow before binding it but column.contains property not working. Don’t know what I am missing here.

Here is the code:

 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

Solution:

This following solution provided by @ajakblackgoat works absolutely fine.

 If dt.Select("ColumnName='ID'").Count = 1 Then obj.VisitID = CType(dr("ID"), Integer)

I have come up with other two solutions and it might help others.

Alternate Solution I:

    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)

Alternate Solution II:

    Dim dt As New DataTable

    dt.Load(reader)

    If dr.Table.Columns.Contains("ID") Then obj.VisitID = CType(dr("ID"), Integer)

Upvotes: 0

Views: 5706

Answers (1)

ajakblackgoat
ajakblackgoat

Reputation: 2139

your reader.GetSchemaTable returns all columns information of the reader. So you have to find the column name as record instead of column.

Use the below code to check if the column name exists in the reader:

Dim dt As DataTable = dr.GetSchemaTable

If dt.Select("ColumnName='ID'").Count = 1 Then
    ' column name exists
End If

Upvotes: 1

Related Questions