62

I am reading an XML file into a DataSet and need to get the data out of the DataSet. Since it is a user-editable config file the fields may or may not be there. To handle missing fields well I'd like to make sure each column in the DataRow exists and is not DBNull.

I already check for DBNull but I don't know how to make sure the column exists without having it throw an exception or using a function that loops over all the column names. What is the best method to do this?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Bryan Anderson
  • 15,969
  • 8
  • 68
  • 83

4 Answers4

182

DataRow's are nice in the way that they have their underlying table linked to them. With the underlying table you can verify that a specific row has a specific column in it.

    If DataRow.Table.Columns.Contains("column") Then
        MsgBox("YAY")
    End If
John Chuckran
  • 2,339
  • 3
  • 18
  • 18
23

You can use DataSet.Tables(0).Columns.Contains(name) to check whether the DataTable contains a column with a particular name.

Matt
  • 74,352
  • 26
  • 153
  • 180
Phillip Wells
  • 7,402
  • 9
  • 43
  • 41
3

Another way to find out if a column exists is to check for Nothing the value returned from the Columns collection indexer when passing the column name to it:

If dataRow.Table.Columns("ColumnName") IsNot Nothing Then
    MsgBox("YAY")
End If

This approach might be preferred over the one that uses the Contains("ColumnName") method when the following code will subsequently need to get that DataColumn for further usage. For example, you may want to know which type has a value stored in the column:

Dim column = DataRow.Table.Columns("ColumnName")
If column IsNot Nothing Then
    Dim type = column.DataType
End If

In this case this approach saves you a call to the Contains("ColumnName") at the same time making your code a bit cleaner.

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
-3

You can encapsulate your block of code with a try ... catch statement, and when you run your code, if the column doesn't exist it will throw an exception. You can then figure out what specific exception it throws and have it handle that specific exception in a different way if you so desire, such as returning "Column Not Found".

Anders
  • 12,088
  • 34
  • 98
  • 146
  • 8
    It is always a better idea to check for errors without having to resorting to a try...catch block; it should only be used as a last resort. –  Feb 22 '10 at 09:05
  • While it is bad design, Anders is correct it would work. It may not deserve an up-vote, but certainly doesn't deserve a downvote. – Jeff Apr 04 '18 at 20:52