views:

33

answers:

2

I have a form that allows a user to import a spreadsheet. This spreadsheet is generally static when it comes to column headers, but now the users want to be able to include an optional column (called Notes). My code crashes when I try to read the column from the spreadsheet if it doesn't exist.

        Dim objCommand As New OleDbCommand()
        objCommand = ExcelConnection() 'function that opens spreadsheet and returns objCommand

        Dim reader As OleDbDataReader
        reader = objCommand.ExecuteReader()

        While reader.Read()
            Dim Employee As String = Convert.ToString(reader("User"))
            Dim SerialNUM As String = Convert.ToString(reader("serialno"))
            **Dim Notes As String = Convert.ToString(reader("notes"))**

If the spreadsheet contains a Notes column, all goes well. If not, crash. How can I check to see if the Notes column exists in the spreadsheet to avoid the crash?

+1  A: 

Perhaps OleDbDataReader.FieldCount could help you program a workaround.

SeaDrive
Both of you got me looking in the right direction..thank you!
Chris Phelps
+1  A: 

Change the code to something like this: [EDIT - changed code logic)

Dim fieldCount = reader.FieldCount 
For i = 0 To fieldCount - 1
Dim colName = reader.GetName(i)
If (colName = "notes") Then
    Dim Notes As String = reader.GetString(i)
End If
Next i
Mikael Svenson
Thank you both for the answers. GetOrdinal("Notes") still threw an error if that column didn't exist, but reader.GetName(4) = "Notes" works..as long as the customer makes sure the Notes column is in the right place.
Chris Phelps
@Chris, I changed the logic of my example. This way you iterate the columns, and check if they match something you want to, instead of assuming the column exist.
Mikael Svenson