How do I find out if a column exists in a VB.Net DataRow

108,966

Solution 1

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

Solution 2

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

Solution 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.

Share:
108,966
Bryan Anderson
Author by

Bryan Anderson

StackOverflow careers CV. Linked In Twitter

Updated on March 10, 2020

Comments

  • Bryan Anderson
    Bryan Anderson about 4 years

    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?